- Home /
Other
How to make the bullet rotation (by 90 degrees) in the direction of movement?
I have 2D bullets in a simple simulation (with Circle Collider 2D).
It is based on a simple script, that I join.
How to make the bullet bounce off the wall change the rotation by 90 degrees in the direction of movement?
The first and third picture shows how the bullet should move.
The fourth picture shows how the bullet moves.
Could someone help and explain?
Script:
private Rigidbody2D rb;
float constantSpeed = 10f;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
rb.velocity = new Vector2 (6f, 6f);
}
// Update is called once per frame
void Update() {
rb.velocity = constantSpeed * (rb.velocity.normalized);
}
Answer by oroora6_unity · Apr 03, 2018 at 05:06 PM
If you're using unity physics your rigidbody should have a velocity, which is a Vector3 which is the distance from a point which in our case is the center of the world (0,0,0). This makes it possible to get a rotation from a Vector by calculating the direction of the distance, luckly for us the vector3 defines that already and unity has a built in method in the Quaternion class to calculate it already. so all you need to do is:
//Play this when the direction of your bullet changes, so after a collision
Rigidbody2D rb = GetComponent<Rigidbody2D>();
transform.rotation = Quaternion.LookRotation(rb.velocity);
Hope it helps!
Answer by Cornelis-de-Jager · Apr 03, 2018 at 02:04 AM
Try this:
void Update() {
rb.velocity = constantSpeed * (rb.velocity.normalized);
// Make it look in direction of travel
transform.LookAt ( transform.Position + rb.velocity );
}
Thanks for your answer, but there is an error after adding script:
error CS0121: The call is ambiguous between the following methods or properties: UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)' and
UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)'
Answer by ngoson107 · Apr 03, 2018 at 02:11 AM
You can create physic material 2d, then change index bounce of physic material 2d. Then add physic material 2d to material of Circle Collider.
Thank you for your answer.
You probably didn't notice, but I wrote that the bullet is bouncing.
This is possible because it contains physic material 2d.
The problem is not bounce, but no rotation in the direction of movement.
But anyway, I'm grateful for the answer :)
Answer by meat5000 · Apr 03, 2018 at 10:23 PM
On Collision, Find the ContactPoint2D.normal and use it to find the angle difference between the projectile and normal. Use it to work out how much rotation your bullet needs.