So I have a script that I want to force the object to look in the direction its velocity is taking it. (or possibly 180 degrees of it, depending on the orientation of the 2D collider it’s using.)
However, it seems at random, the object snaps to 90 degrees for no apparent reason, and the collider points in an odd direction.
So i’m at my wit’s end here, anyone have any idea what to do?
Here’s the code that forces rotation in velocity (Note that the object will bounce around, so direction changes will occur)
private Vector3 dist = new Vector3();
private Vector3 distprevframe = new Vector3();
private Vector3 dir = new Vector3();
void Update () {
dist = transform.position;
dir = dist - distprevframe;
dir = dir * 90;
distprevframe = transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle + 90, Vector3.forward);
Also, since I think it’s relevant, here is the code for the object being spawned
Rigidbody2D Shot;
Shot = Instantiate (ProjectileTest, target.position, Quaternion.Euler (Vector3.forward)) as Rigidbody2D; //target is where the object is spawned.
Shot.velocity = transform.TransformDirection (Vector3.forward * bulletspeed);
Shot.transform.Rotate (Vector3.forward);