Hello, I am using a script where an object follows my character. The only problem was the object didn’t stay on the ground. Someone suggested I add a raycast to the ground so the object will not float. I am new to raycasting and I cannot get this script to compile. (compiler error says I’m 2 missing semicolons).
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);
//RAYCAST ADDED HERE
RaycastHit myHit;
float offsetAlign = 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;
}
You are using C# syntax for the variable declarations at line 24 and 25. Check lines 1-3 for the actual syntax.
Line 28 has another issue because myHit.point and you are adding a float to it. It should probably be myHit.point.y.
Thank you for the reply. This worked great as far as keeping the object on the ground, but as it moves toward me the object passes other objects in the world even though generate colliders are on for both objects… Any ideas on how to fix this? Here is the code I am using with Dantus’ fixes:
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);
//EDIT DONE HERE
var myHit : RaycastHit;
var offsetAlign : float; //Add offset to make your object align perfect to terrain
offsetAlign = 0;
if(Physics.Raycast (myTransform.position, Vector3.down, myHit))
{
myTransform.position.y = myHit.point.y + offsetAlign;
}
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}