- Home /
making an object stop responding with an object at a certain distance away
i have a turret aiming at my character, how do i get it to stop when my character is at a certain distance?
var LookAtTarget:Transform;
var damp = 6.0;
var laserPrefab:Transform;
var savedTime=0;
function Update () {
if(LookAtTarget) { var rotate = Quaternion.LookRotation(LookAtTarget.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
var seconds : int = Time.time;
var oddeven = (seconds % 2);
if(oddeven)
{
Shoot(seconds);
}
}
} function Shoot(seconds) { if(seconds!=savedTime) { var laser = Instantiate(laserPrefab ,transform.Find("bang").transform.position, Quaternion.identity); laser.gameObject.tag = "Untagged";
laser.rigidbody.AddForce(transform.forward * 10000);
savedTime=seconds;
}
}
thanks :D
Answer by The_r0nin · Dec 26, 2010 at 01:05 AM
Add in the Update function:
if (Vector3.Distance(lookAtTarget.position,transform.position) <= 10){
// your code here.
}
Two points of advice. First, naming conventions in Unity/Javascript usually begin variables with a lowercase letter and functions with an uppercase one (i.e. lookAtTarget, as opposed to LookAtTarget()...). It will help you keep track of what you are doing (and you'll be surprised at how easy it is to lose track).
Second, you might want to test against the square of the distance you want rather than the distance. Every square root sucks up more computing power, and the end result is the same. Your code would look like:
if ((lookAtTarget.position-transform.position).sqrMagnitude <= 100){ // 100 is 10 squared
yeah i do know how easy it is 2 lose track, haha, god scripting is confusing!!!! thanks 4 the help and pointers, :D
oh you say // your code here, is that the code i posted as a question??
Yes. Check the distance, then have it rotate to your character (put everything in your Update function in this).
Also, if this works for you, click the checkmark next to the answer so everyone will know that it is solved.
the only problem is that it says error "expecting "(" found "Update" :/
Your answer
Follow this Question
Related Questions
camera zoom in/out position based on object's speed 1 Answer
Enemy Jitters when i want him to stop a certain distance 0 Answers
Lerp in direction to certain distance 3 Answers
Rotating object towards mouse point 1 Answer
Odometer for a racing game 2 Answers