- Home /
Enemy doesn't face player
Hello! I'm trying to make a game with a basic enemy that rotates towards the player and moves towards it. This is the code I'm using (I'm very new to unity, so I did not write this myself.)
var target : Transform;
public var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;
function Awake()
{
myTransform = transform;
}
function Start()
{
//Target the player
target = GameObject.FindWithTag("Player").transform;
}
function Update ()
{
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
//Rotate towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime);
//Move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
And it seems to think that in this position it's facing the player.
I've tried things like having it face the gun (the blue object in the picture. It's a pet carrier), and use transform.LookAt(target), but it doesn't seem to be working. This makes me think the direction of my player object must be off, but I don't know how I'd fix that. Any ideas?
Thank you for your time.
EDIT: I was just playing around in blender and thought it might work if I just rotated the object. So, I rotated it 90 degrees on the z-axis, and now it works perfectly. Sorry to bother (:
For 3D, Unity expects the front of the player to facing positive 'z' and the top of the player facing positive 'y' when the rotation is (0,0,0). You can fix this in your modeling program, or you can fix this by using an empty game object as a parent and rotating the child so that when the parent has rotation (0,0,0), the child, visible object is facing the correct direction.
Sorry, I'm such a noob >.>
So, let me see if I get this. Add an empty game object with the rotation of (0,0,0). Rotate the enemy(?) to be facing the player. $$anonymous$$ake the enemy the child of the empty game object. Or did I totally misunderstand things?
Add an empty game object with rotation of (0,0,0). Add your visible game object as a child at the same position. You an set the position to (0,0,0) in the inspector after adding the visible object as a child. Next rotate the visible object so that it is facing positive 'z'. Scripts or references use the empty game object.
Your answer
Follow this Question
Related Questions
How do I make my imported 3d model face the player? 1 Answer
mouse over for 3d menu 1 Answer
Help with Enemy AI 1 Answer
Changing 3d text through script 1 Answer
[js] How To Check If The Player Is Facing An Object 3 Answers