Endless Jumping
Scorri per mostrare il menu
Platforms & Jumping with Collisions
We can now move left and right - but to make an endless jumper, we need consistent, controlled jumping.
If we simply rely on physics bounciness, the player will always bounce to the same height, which doesn't work well for an endless game. Instead, we'll apply a fixed upward velocity whenever the player lands on a platform.
Creating the Platform Script
This logic belongs on the platform, not the player.
- select the platform GameObject;
- add a new script called
PlatformScript; - place it in the Scripts folder.
Before writing C#, we define the behaviour in pseudocode:
// When the player collides with the platform,
// add upward velocity to the player equal to jumpStrength
// Then destroy the platform
Responding to Collisions
This behavior should not go in Start() or Update(). To react to a collision, we use Unity's collision callback:
OnCollisionEnter2D(Collision2D collision)
This function:
- runs only when a collision occurs;
- requires at least one object involved to have a Rigidbody2D;
- provides information about the other object involved in the collision.
Detecting the Player
Since this script is attached to the platform, the other object in the collision is the player.
We use an if statement to check whether the colliding object is the player, based on its name.
- the check is case-sensitive;
- useful for simple prototypes and learning.
Printing to the Console is a good way to confirm the collision is working before adding gameplay logic.
Applying Jump Velocity
To control the jump height, we introduce a variable:
jumpStrength (float)
When the player collides with the platform:
- get the player's Rigidbody2D;
- set its y-axis velocity to jumpStrength.
This ensures the player always jumps the same height, no matter which platform they land on.
Destroying the Platform (Optional)
To make the platform behave like a bubble, we can destroy it after the jump:
- destroying the platform GameObject;
- happens after the jump force is applied.
This creates a satisfying "pop" effect and prevents reuse of the same platform.
Result
You now have:
- player-controlled movement;
- platforms that launch the player upward;
- optional disappearing platforms.
With this alone, you can already build a playable endless jumper.
1. Which Unity function is used to run code only when a collision occurs?
2. Which of the following is required for OnCollisionEnter2D() to detect a collision?
3. You want the player to jump a fixed height when colliding with a platform. Which pseudocode best describes this behavior?
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione