- Home /
how to move an object, but make it stay on the ground
im working on an enemy in my game that will shoot the player from a vertain distance, but move towards him and use melee attacks if it gets closer. everything for it is working so far except when my player jumps, the enemy follows it in the air. The line im using to make it follow the player is transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
the problem is that im also making him rotate towards the players location so it can shoot from a distance
Quaternion rotation = Quaternion.LookRotation (target.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
so how can i make him move toward the players location, but not be floating in the air to follow him when he jumps?
Answer by wibble82 · Dec 08, 2015 at 05:12 PM
Hi
By default transform.Translate operates in local space, hence you being able to use 'vector3.forward' - i.e. move along your own forward (z) axis. That works fine until, as you say, your player jumps!
As you want to do something based on world space now ('up' from the point of view of the world) you'll need to start moving based on world space values. The simplest way I can see of writing this code in your game might be:
//get our forward in world space
Vector3 my_forward = transform.forward;
//clear the y so we dont move up or down
my_forward.y = 0;
//normalize it, so we have a unit vector even after chopping out the y bit
my_forward = my_forward.normalized;
//scale it by the amount we want to move
my_forward *= moveSpeed * Time.deltaTime;
//and do our translation in world space
//(could be written transform.position += my_forward)
transform.Translate(my_forward, Space.World);
//or on much fewer lines!
//Vector3 my_forward = transform.forward;
//my_forward.y = 0;
//transform.position += my_forward.normalized * moveSpeed * Time.deltaTime;
Lots of ways to write it that may vary depending on your situation, but that's the basic concept - get the direction you want to move, chop out the bits you don't want, renormalize it and then move by however much you want.
-Chris
Your answer
Follow this Question
Related Questions
How to predict position of object before transform.translate will apply? 1 Answer
How to stop a unit from rotation once it gets to designated position? 2 Answers
Interpolating the motion of a camera moving from one node to another 1 Answer
Determining the rotation of an object based on its upcoming position? 1 Answer