- Home /
Unity2D, how to stop game when colliding with an object or speed is 0?
I am making a Impossible game/geometry dash copy just to learn a few things and so, I am not intending on releasing it.
Anyway, I am trying to find a good way to move my cube in a constant speed to the right, but if you collide with an object and your velocity or movement is 0, the game should end as you are not allowed to stop nor hit the side of objects.
Currently my code of applying speed to the object is this:
rb = GetComponent<Rigidbody2D>();
var newVelocity = rb.velocity;
newVelocity.x = maxSpeed * 7;
rb.velocity = newVelocity;
I also have applied a rigidbody to my cube and I am really happy with the movement and the feeling of the controls, tho I am stuck at a point.
How would I do so when the cube hits the side of obstacle or another object and the velocity is 0 the game stops?
I tried a bunch of things such as when the velocity is 0 kill the game, but my code for movement is always setting the velocity to 7, therefor that won't work.
I also tried adding a collision detection system on the right of the object like so: That didn't work either as the jump animation rotates the cube 90 degrees and then the box collider will be at the bottom where the cube lands, and therefor kills the game at that point.
I tried alot of things I just dont know how to solve it, can anyone share me some ideas how to solve it, do I have to change my movement code a bit or what should I do?
Appreciate all the help I can get, thanks.
Answer by Spartan0751 · Aug 24, 2015 at 11:58 AM
One thing you could do is check what the velocity is before you set it. After a few tests, assuming you're using FixedUpdate, it seems the velocity does register as 0 if you check it before you set it, which makes sense.
rb = GetComponent<Rigidbody2D>();
var newVelocity = rb.velocity;
if(newVelocity == 0)
// Do things here
else {
newVelocity.x = maxSpeed * 7;
rb.velocity = newVelocity;
}
This way, you'll know if its velocity is nil, and if it isn't you can continue to make it move as normal.
Your answer
Follow this Question
Related Questions
2D Platformer Jumping at a 45 degree angle 2 Answers
2d collider stuck issue 1 Answer
Moving colliders that are part of a composite collider 1 Answer
Velocity in Unity2D 2 Answers
Constant velocity when colliding - 2D 0 Answers