Rivals
AR PVP shooter where you battle zombies in real life to earn $RIVAL tokens.
Problem Statement
Rivals is a revolutionary Augmented Reality (AR) multiplayer shooter that transforms the real world into a competitive gaming arena. This isn't just a mobile game—it's a sophisticated fusion of Unity AR Foundation, blockchain economics, and AI-driven gameplay that creates a persistent, location-based gaming ecosystem where players compete for cryptocurrency rewards.The project represents the next evolution of mobile gaming, combining the immersive AR experience of apps like Pokémon GO with the competitive intensity of first-person shooters, all powered by Web3 tokenomics that give real monetary value to in-game achievements.Key Features:Zombies patrol randomly within your detected spaceThey scream when they first spot you (Alert state)They chase aggressively using pathfinding around real furniture/obstaclesThey attack when within 1.5 metersThey react to damage with hit animationsFull death sequence with cleanupUnity AR Game Architecture:Core AR Foundation ImplementationThe Unity application leverages AR Foundation to create a sophisticated augmented reality experience:Dynamic Environment MappingARPlaneManager: Real-time detection of horizontal and vertical surfaces (floors, walls, tables)ARNavMeshBuilder: Automatically generates navigation meshes from detected AR planes, allowing AI enemies to pathfind through your real environmentARFeatheredPlaneMeshVisualizerCompanion: Visualizes detected surfaces with smooth, feathered edges for better user feedbackARRaycastManager: Enables precise interaction with the real world for object placement and shooting mechanicsAdvanced AI System The game features a sophisticated 6-state AI system for zombie enemies:States: Patrol → Alert → Chase → Attack → Hit → DeathZombieAI Components:ZombieVision: Field-of-view detection (120° cone, 8-12m range) with line-of-sight checkingZombieMovement: NavMesh-based pathfinding that respects real-world obstaclesZombieAttack: Melee combat system with range validation and damage dealingZombieHealth: Health management with visual feedback and death animationsZombieSpawner: Dynamic enemy spawning system that considers AR plane availabilityShooting & Combat MechanicsZombieShooter: Screen-center aiming with crosshair targetingBullet System: Physics-based projectiles with collision detectionCrosshairController: Dynamic UI that changes color based on game modePlayerHealth: Damage feedback with screen flash, health bar, and audio cuesLocation-Based FeaturesLocationMonitor: GPS tracking for player movement and trap discoveryReal-time location updates sent to server every few secondsProximity detection for discovering other players' trapsGeofencing for trap activation (within ~10 meters)Blockchain Integration and Smart Contract ArchitectureThe game uses a custom ERC-20 token contract (RivalsToken.sol) deployed on multiple chains:Supported Blockchains:Flow Testnet (Chain ID: 545)Chiliz Spicy Testnet (Chain ID: 88882)Local Anvil (for development)Token Economics ($RIVAL):// Rewards killMonster() → +1 RIVAL token per zombie kill // Penalties dieByMonster() → -20% of current balance dieByTrap() → -20% transferred to trap owner // Costs placeTrap() → -1 RIVAL tokenSmart Contract Functions:killMonster(address): Mints 1 RIVAL token when player kills a zombiedieByMonster(address): Burns 20% of player's tokens when killed by AIdieByTrap(address, address): Transfers 20% from victim to trap ownerspend(address, uint256)`: Burns tokens for trap placementWeb3 InfrastructureAuthentication & Wallet Management:Privy Provider: Web3 authentication with social login supportWalletConnect: Mobile wallet integrationCross-chain support: Automatic chain switching via WagmiReal-time Blockchain Integration:Viem: Modern Ethereum client for contract interactionsAutomatic transaction handling: Server manages all blockchain callsBalance tracking: Real-time token balance updatesTransaction receipts: Full on-chain verificationDatabase & Server Architecture**API Endpoints:/api/movement(Location Tracking)Receives GPS coordinates from Unity appUpdates player's last_active timestampReturns nearby traps within discovery radiusFetches real-time token balance from blockchain/api/kill-monster(Zombie Elimination)Increments player's kill_count in databaseTriggerskillMonster()smart contract callAwards 1 RIVAL token on successful transaction/api/place-trap(Strategic Placement)Validates player has ≥1 RIVAL tokenCallsspend()to burn 1 tokenStores trap location in PostGIS databaseReturns trap ID for Unity game object/api/die(Death Handling)Death by Monster: Burns 20% of player's tokensDeath by Trap: Transfers 20% to trap ownerUpdates game state and statisticsGame Flow & User ExperiencePlayer Onboarding:Download Unity AR appConnect Web3 wallet (Privy authentication)Grant location & camera permissionsAR plane detection** begins automaticallyTutorial: Learn shooting, movement, trap placementCore Gameplay Loop:Explore Real Environment: Move around your space as zombies spawnCombat: Shoot zombies using screen-tap controls with AR crosshairEarn Tokens: Each kill awards 1 RIVAL token via blockchain transactionStrategic Placement: Spend tokens to place invisible traps at GPS locationsCompetitive PvP: Other players walking near your traps lose 20% of their tokens to youRisk/Reward: Death means losing 20% of your token balanceSocial & Competitive Features:Real-time Leaderboards: Rankings by kills, tokens, survival timePlayer Profiles: Track individual stats and achievementsTrap Networks Create strategic trap placement patternsLocation-based Competition: Battle for control of high-traffic areasTokenomics & MonetizationToken Utility ($RIVAL):Earning: 1 token per zombie killSpending: 1 token per trap placementRisk: 20% loss on death (to monster or trap)Reward: 20% gain when your trap kills another playerEconomic Incentives:Skill-based Rewards: Better players accumulate more tokensStrategic Depth Trap placement creates passive income streamsHigh Stakes: Death penalty creates tension and careful gameplaySocial Competition: Leaderboards drive engagementUnique Value PropositionsTrue AR Integration Unlike superficial AR filters, Rivals uses real environment mapping for gameplay. Zombies navigate around your actual furniture, and the game adapts to your physical space.Genuine Web3 Economics Not just NFT collectibles—real monetary incentives where skill directly translates to cryptocurrency earnings through competitive gameplay.Location-Based Strategy GPS-integrated trap system creates persistent, location-based gameplay where your strategic decisions affect other players across time and space.Cross-Chain Accessibility Multi-blockchain deployment ensures players aren't locked into one ecosystem, with seamless chain switching.Sophisticated AI State-machine driven zombie AI with realistic pathfinding, vision systems, and behavioral complexity that rivals AAA games.Market PositionRivals occupies a unique intersection:AR Gaming (Pokémon GO, Harry Potter Wizards Unite)Battle Royale/Shooter (PUBG Mobile, Call of Duty Mobile)Play-to-Earn (Axie Infinity, StepN)Location-based Gaming (Ingress, Geocaching)It's positioned as thefirst truly competitive AR shooterwithreal cryptocurrency rewards, targeting the growing market ofWeb3 gamingenthusiasts who want skill-based earning opportunities.This is a groundbreaking project that could define the future ofmobile AR gamingby proving that immersive augmented reality experiences can be both technically sophisticated and economically rewarding for players.
Solution
Technical Architecture OverviewRivals represents a complex fusion of Unity AR Foundation, blockchain economics, and real-time geospatial system. Here's how we solved some gnarly technical challenges to create a persistent, location-based AR shooter.Unity AR Game Engine - The Core ChallengeDynamic AR NavMesh Generation The Problem: Traditional games pre-bake navigation meshes, but AR environments are completely unknown until runtime. How do you make AI zombies navigate around a user's real furniture?Our Solution: We built a real-time NavMesh builder that converts AR Foundation plane data into navigable surfaces. When AR Foundation detects a horizontal plane (like a floor), we automatically create a NavMesh surface. When it detects vertical planes (like walls), we create NavMesh obstacles that AI can't walk through.Technical Innovations:Real-time conversion: AR planes become NavMesh surfaces in millisecondsPerformance optimization: Batched rebuilding every 2 seconds instead of per-frameObstacle carving: Vertical planes automatically become NavMesh obstaclesMemory management: Dynamic cleanup when planes are removed/updatedCross-Platform Input System The Challenge: Handle both mouse (editor) and touch (mobile) seamlessly while preventing conflicts between shooting and mine placement modes.We created a mode-aware input system that detects both mouse and touch input simultaneously, but only processes it when in the correct mode. This prevents accidentally shooting when trying to place mines, and ensures smooth gameplay across development and mobile platforms.GPS + AR Coordinate Fusion - The "Indoor GPS" ProblemThe Challenge: GPS coordinates are in latitude/longitude, but Unity works in local 3D space. GPS accuracy indoors is terrible (±10-50 meters).Our Hacky-But-Brilliant Solution: Instead of trying to solve GPS accuracy (impossible), we abandoned absolute positioning and used proximity-based discovery. When the server detects you're within ~10 meters of a trap's GPS coordinates, it tells Unity to spawn the trap "somewhere in front of you" using AR raycasting to find the actual ground.Why This Works:Completely sidesteps the indoor GPS accuracy problemUses AR plane detection for accurate ground placementCreates consistent UX regardless of GPS precisionPlayers still get the location-based gameplay without GPS frustrationBlockchain Integration - Zero-Friction Web3Server-Controlled Wallet Architecture The Challenge: Web3 games typically require users to manage wallets, sign transactions, pay gas fees. Terrible UX.Our Solution: The server owns the "game wallet" and pays all transaction costs. When a player kills a zombie, Unity sends an API call to our server, which then executes the blockchain transaction to mint tokens. Players never interact with crypto directly - they just see their token balance increase.Technical Benefits:Zero gas fees for players (server pays)No wallet management requiredInstant transactions (no waiting for user signatures)Cross-chain abstraction (server handles chain switching)Multi-Chain Smart Contract Strategy We deployed the same contract across multiple testnets on with Flow and Chiliz using Foundry. Our smart contract is simple but effective - it mints 1 token per zombie kill, burns 20% of tokens when you die to monsters, and transfers 20% between players when traps are triggered.Partner Technology: Privy provides Web3 authentication, but cleverly, the server holds the "game wallet" that actually executes transactions.Database & Geospatial ArchitecturePostgreSQL earthdistance for Location Logic The Choice: We used PostgreSQL'searthdistance extensioninstead of PostGIS for geospatial queries.Why earthdistance over PostGIS:**Lightweight: No need for full PostGIS overhead for simple distance calculationsBuilt-in to PostgreSQL: earthdistance comes with most PostgreSQL installationsPerfect for point-to-point distance: Exactly what's needed for trap proximity detectionEarth-curvature aware: Accurate distance calculations using the cube extensionThe server calculates distances between player GPS coordinates and all existing traps using earthdistance functions, returning nearby traps to the Unity client for spawning.Unity-to-Server CommunicationThe Challenge: Mobile games need robust networking, but Unity's networking is overkill for simple API calls.Our Streamlined Solution: Direct HTTP API calls using Unity's UnityWebRequest. We have four main endpoints:Movement API: Receives GPS coordinates, returns nearby traps and token balanceKill Monster API: Increments kill count, triggers blockchain token mintingPlace Trap API: Validates token balance, burns tokens, stores GPS locationDie API: Handles death penalties (burn tokens or transfer to trap owner)AI System ArchitectureWe implemented a sophisticated 6-state AI system for zombie enemies: Patrol → Alert → Chase → Attack → Hit → Death.ZombieVision Component: Handles field-of-view detection with a 120° cone and 8-12 meter range, plus line-of-sight checking that respects AR plane obstacles.ZombieMovement Integration: Uses the dynamically-built NavMesh to pathfind around real-world furniture and obstacles detected by AR Foundation.Smart State Management: Zombies patrol randomly within detected space, scream when they first spot you, chase aggressively using pathfinding, and attack when within 1.5 meters.Performance Optimizations & Notable HacksThe GPS Indoor Hack Instead of trying to solve GPS accuracy indoors (impossible), we gave up on absolute positioning and used proximity-based discovery. This turned a technical limitation into a feature.The Blockchain Gas Hack Instead of making players pay gas fees (terrible UX), the server owns a wallet and pays all transaction costs. Players never touch crypto directly but still get real Web3 ownership.The Cross-Platform Input Hack Instead of using Unity's complex Input Actions system, we detect both mouse and touch simultaneously in every Update() and let the first one win. Simple but bulletproof.The NavMesh Dynamic Building Hack Instead of trying to build perfect NavMesh from AR data, we use "good enough" box colliders that represent detected planes and let Unity's NavMesh system handle the pathfinding details.Trap Spawning Optimization We prevent duplicate trap spawning with smart caching - each trap ID is tracked in a dictionary to ensure it only spawns once, even if the GPS proximity detection triggers multiple times.AR Plane Performance Optimization We batch process planes (max 5 per frame) and only rebuild NavMesh every 2 seconds instead of every frame, preventing performance drops during intensive AR scanning.Technology Stack Choices & Rationale**Unity AR Foundation Next.js + TypeScript PostgreSQL + earthdistance Foundry Viem + WagmiMost Notable Technical Achievements**Solved the "Indoor GPS" problem by abandoning absolute positioning for proximity-based discoveryCreated seamless Web3 UX by having server pay all gas fees while preserving token ownershipBuilt dynamic AI navigation that works in any real-world environment using AR plane conversionAchieved cross-platform compatibility with unified input handling for mobile and desktopImplemented real-time geospatial gameplay using lightweight PostgreSQL extensions instead of complex GIS systemsThe most impressive hack is probably how we turned GPS inaccuracy from a limitation into a feature - instead of fighting physics, we embraced "approximate location" and made it part of the game design. Players get location-based gameplay without the frustration of precise positioning requirements.This project demonstrates that with clever architecture choices and willingness to work around technical limitations rather than against them, you can create sophisticated AR experiences that feel magical to users while being surprisingly practical to build.
Hackathon
ETHGlobal New York 2025
2025
Prizes
- 🏆
Best Killer App on Flow3rd place
Flow
- 🏆
Flow Builder Pool Prize
Flow
- 🏆
🏆 ETHGlobal New York 2025 Finalist
ETHGlobal
Contributors
- chris13524
28 contributions
- jiyuu-jin
23 contributions
- valist-dev
11 contributions