- Home /
Look at enemy
Whats wrong with this code? Why won't the transform keep looking at the target once the target is in the transforms raycast?
#pragma strict
var damping : int = 6.0;
private var target : Transform;
private var hit : RaycastHit;
function Awake(){
}
function Start(){
}
function Update(){
if (Physics.Raycast (transform.position, transform.forward, hit, 100)) {
Debug.DrawRay(transform.position, transform.forward*100.0, Color.red);
target = hit.transform;
if(target.tag == "Enemy"){
lookAt();
}
}
}
function lookAt(){
var rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
Comment
just use the supplied fucntion LookAt. "look at" the doco :)
Scroodge$$anonymous$$, Thanks, but didn't work ..
Fattie, Thanks, much easier ..
Best Answer
Answer by Griffo · Aug 30, 2012 at 08:56 AM
#pragma strict
private var target : Transform;
private var hit : RaycastHit;
function Awake(){
}
function Start(){
}
function Update(){
if (Physics.Raycast (transform.position, transform.forward, hit, 100)){
Debug.DrawLine (transform.position, hit.point, Color.red);
if(hit.transform.tag == "Enemy Terrorist"){
target = hit.transform;
LookAtIgnoreHeight();
}
}
}
function LookAtIgnoreHeight () {
print(hit.transform);
var lookAtPos : Vector3 = target.position;
//Set Y of LookAt target to be Players height.
lookAtPos.y = transform.position.y;
transform.LookAt (lookAtPos);
}