- Home /
How to rotate a projectile and mantain constant speed when hitting a wall? 2D
Hi, everyone. I am doing a top-down 2d game where i have a character that shoots bullets. As soon as these bullets are shooted, they are going around in the scene forever till the round has not finished. My point is that i cant rotate the projectile in a manner so that it does the reflection to the wall correctly and continue going around through the scene at constant speed.
I searched and founded that i need a wall with a rigidbody and a rigidbody on the projectile, both with drag to 0 and freeze rotation, and gravity set to 0. Also the respective colliders on it and the following script: (note that "Opponent" is the wall in this case)
void OnEnable() { rb = GetComponent<Rigidbody2D>(); rb.velocity = transform.right * speed; } void OnCollisionEnter2D(Collision2D collision) { if (collision.transform.CompareTag("Opponent")) { Vector3 reflectedPosition = Vector3.Reflect(transform.right, other.contacts[0].normal); rb.velocity = (reflectedPosition).normalized * speed; //rotate Vector3 dir = rb.velocity; float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; rb.MoveRotation(angle); } }
I tried it many times but it still does not work. The projectile moves in strange ways, sometimes it doesnt reflect properly, rotation does not occur and it slows down and speed up at an unexpected speed. I am really struggling to find a solution, so i am writing here, maybe someone could help me out.
PS: I also dont know how to put correct rotation if i want to face it up or down depending on which direction i am looking with my character (for left and right i just use Flip, because if i change z rotation it mess up even more)
I am so thankful of everyone could help me out on this! Cheers, Ogim