I’m a complete C# noob. I recently got a textbook from Amazon to teach myself game dev on Unity and have been following through one of the written tutorials with the goal of completing an endless side-scrolling game.
Here’s the context:
I have different game states such as Start Menu, New Game, and Game Over.
The game state is set to begin with “New Game” by pressing the “S” key, which will drop the sprite from a starting point
Sometimes, if I wait a while after the sprite has fallen through the bottom of the screen, when I hit S the new game state instance will retain the velocity of the prior one, causing the sprite to clip right through the platform.
What’s the best way to reset the sprite velocity to “0” or limit the maximum fall speed so the sprite doesn’t just crash through the platform like this? I’ve included a GIF of the behavior as an illustration.
You can reset the velocity with: GetComponent().velocity = Vector2.zero;
There are several methods you can use to limit the speed of the object. You could use Rigidbody2D’s Linear Drag to slow down the sprite. Or you could do it in code:
Thanks for point me in the right direction! I’m having trouble plugging the code though. I’m getting a red underline beneath “maxVelocityY” in MSVS. Should I create a private float somewhere to define maxVelocity?
Thanks again! So, after bashing my head against the keyboard I wanted to share a smaller piece of code I eventually arrived on:
rigidBody.velocity = Vector3.zero;
I have two different .cs scripts: PlayerController and GameManager. PlayerController handles things like the jump force and running speed, while GameManager controls the different scene triggers. Under PlayerController, I was able to insert the above code under a method I called “StartGame” - which is triggered by a GetButtonDown from the GameManager script.
Anyway, I tucked “rigidBody.velocity = Vector3.zero;” under StartGame() in PlayerController and it worked.
Worth reading about components and so on, plus script execution order, start, awake, update, lateupdate and fixedupdate when you get time, these are all good places to tuck something