3
\$\begingroup\$

I'm creating a simple tank game. No matter what I do, the turret keeps facing the target with it's side. I just can't figure out how to turn it 90 degrees in Y once so it faces it correctly. I've checked the pivot in Maya and it doesn't matter how I change it.

This is the code I use to calculate how to face the target:

void LookAt()
{

    var forwardA = transform.forward;
    var forwardB = (toLookAt.transform.position - transform.position);

    var angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    var angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;

    var angleDiff = Mathf.DeltaAngle(angleA, angleB);
    //print(angleDiff.ToString());
    if (angleDiff > 20) {
        //Rotate to 
        transform.Rotate(new Vector3(0, (-turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else if (angleDiff < 20) {
        transform.Rotate(new Vector3(0, (turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else {

    }
}

I'm using Unity3d and would appreciate any help I can get! Thanks!

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Why are you doing the math at all instead of a helper function or two?

For example, Quaternion.LookRotation( Vector3 forward )

\$\endgroup\$
2
  • \$\begingroup\$ How would I control the speed of rotation with that example? Thanks! \$\endgroup\$
    – Phil
    Commented Feb 6, 2011 at 23:40
  • \$\begingroup\$ Calculate your target rotation with that. Then you can lerp to it or use something like the rotateto helper function. \$\endgroup\$
    – Tetrad
    Commented Feb 6, 2011 at 23:56
1
\$\begingroup\$

To solve this I kept my code and added a parent object which got the code component instead. Then I turned the child object so that the rotation weirdness disappeared.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .