DzoniGames
DzoniGames

Reputation: 91

JScript -- Unity transform.eulerAngles.y not Working

So last week I started working on an RPG and I've started working on the enemy AI and it should rotate to it's target but it doesn't. What I did is for the enemy I created a child object and put a script that rotates it to the target, then in the enemy script I did this:

if(transform.eulerAngles.y > rotTracker.transform.eulerAngles.y) {

    transform.eulerAngles.y -= 2 * Time.deltaTime;
}
if(transform.eulerAngles.y < rotTracker.transform.eulerAngles.y) {

    transform.eulerAngles.y += 2 * Time.deltaTime;
}

the rotTracker is a GameObject variable. So, what is wrong with this code? The rotation tracker changes rotations but not the enemy. Maybe because it has child objects that look at a different thing? I created a sprite and put it on top of the enemy and it represents the enemies health and always turns towards the camera.

Upvotes: 0

Views: 452

Answers (2)

Gunnar B.
Gunnar B.

Reputation: 2989

You shouldn't use transform.eulerAngles for increment, only fixed values. Also, better set it as vector, not the single axis.

If you've put the the script on the child and actually want to rotate the parent, then you have the wrong transform, but I can't clearly read that.

Further on I'd recommend doing something like this:

var dir = transform.postion - target.position;
dir.y = 0;    // set the axis you want to rotate around to 0
var targetRotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * speed);

speed being a factor for how fast you want to rotate. (I think the code should be correct, I'm using C# though.)

Upvotes: 0

Jamel de la Fuente
Jamel de la Fuente

Reputation: 69

You can't change directly the angles. You need to change the vector positions. For example:

var yRotation -= 2 * Time.deltaTime;    
transform.eulerAngles = new Vector3(0, yRotation, 0);

Hope this helps!

Upvotes: 2

Related Questions