Course Content
Unity for Beginners
Unity for Beginners
Move our Bird
This is the code that we have used to move our bird:
Detailed Explanation
Our script runs within the Update function, which is called every frame by Unity. This is where you can place code that needs to run continuously, ensuring that your game responds to player input and other events in real-time.
Understanding Variables and Components
var oldVelocity = rb.velocity;
- This line declares a variable named
oldVelocity
and assigns it the current velocity of the Rigidbody component attached to the Flappy Bird GameObject; rb
is a reference to the Rigidbody component, which is responsible for simulating physics on the Flappy Bird.
Detecting Key Presses
if (Input.GetKeyDown(KeyCode.Space))
- This line checks if the Space key is pressed down during the current frame;
- This condition ensures that the Flappy Bird jumps only once when the player presses the Space key.
By using this condition, you can make the bird respond to player input, allowing it to jump when the player presses the Space key.
Adjusting Vertical Movement
oldVelocity.y = 6;
- When the Space key is pressed, this line sets the vertical (Y) component of the velocity to 6;
- This change makes the Flappy Bird jump upward, simulating a flap.
By modifying the Y component of the velocity, you control how high the bird jumps each time the player presses the Space key.
Maintaining Horizontal Movement
oldVelocity.x = 4;
- This line sets the horizontal (X) component of the velocity to 4;
- This ensures that the Flappy Bird moves forward at a constant speed.
In the game, the bird typically moves forward automatically. By setting the X component, you maintain its forward momentum, making the gameplay smooth and consistent.
Applying the New Velocity
rb.velocity = oldVelocity;
- This line assigns the modified velocity back to the Rigidbody component attached to the Flappy Bird GameObject;
- It updates the bird's velocity, causing it to move according to the new horizontal and vertical components.
By adjusting the velocity, you control the Flappy Bird's movement, including jumping and forward motion, making the game interactive and engaging.
1. In the provided code, what does rb.velocity
refer to?
2. What Unity class provides access to user input like keyboard presses?
3. What does Input.GetKeyDown(KeyCode.Space)
do in the code?
Thanks for your feedback!