Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

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

For example, Quaternion.LookRotation( Vector3 forward )

share|improve this answer
    
How would I control the speed of rotation with that example? Thanks! –  Phil Feb 6 '11 at 23:40
    
Calculate your target rotation with that. Then you can lerp to it or use something like the rotateto helper function. –  Tetrad Feb 6 '11 at 23:56
up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.