Hello, I am using this script and the object I apply this script to floats in the air as it attempts to follow my character. How can I get the object to remain on the terrain as it follows my character? (the character changes heights on the terrain)
Thank you.
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
I had the exact same problem sometime ago, here is the solution:
The object is floating in the air because it is following the center pivot of your character (which is probably higher than your follower), if you want it to stay on the ground, just create an empty gameObject put it at the height of your character follower, but close to your character and attach it to him, add a tag to it (like targetPoint) and instead of looking for the player, look for that point:
target = GameObject.FindWithTag("targetPoint").transform; //target the player
Easiest way is, you can make a raycast from your object to Vector3.down so you can find the point to snap on each frame.
Edit: I have not test it but possibly similar solution like this:
Edit2 : I have changed the code. i rewrite it for java script. it would still give some possible errors, notify me further
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//EDIT DONE HERE
RaycastHit myHit;
var offsetAlign:float = 0.0; //Add offset to make your object align perfect to terrain
if(Physics.Raycast (myTransform.position, Vector3.down, myHit))
{
myTransform.position.y = myHit.point + offsetAlign;
}
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}