jennes
August 26, 2012, 9:33pm
1
Hi unity. I have an following script on my enemy, and he just walks through the walls even the colliders didn’t work, anyone have one solution?
var target : Transform;
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;
function Awake(){
myTransform = transform;
}
function Start(){
target = GameObject.FindWithTag("Player").transform;
}
function Update () {
var dist = Vector3.Distance(target.position, myTransform.position);
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime);
if(dist > 2.4){
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Piflik
August 26, 2012, 9:35pm
2
You are editing the transform directly. This will always ignore any collision. If you want collision, you have to use forces.
MickM
September 11, 2012, 1:11am
3
As above, you are setting the position directly which will override the physics.
note - Unity - Scripting API: Rigidbody.velocity
(This says you shouldnt modify velocity directly; it works fine for me but bear that in mind if you try it!)
Assuming your enemy has a rigidbody attached, you could try using ‘velocity’ instead.
(So rather than moving the position frame by frame - including specifying a position in the wall; you just set the velocity and the physics engine handles the rest.)
Try replacing
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
with:
myTransform.rigidbody.velocity = Vector3(lookDir.normalized * moveSpeed * Time.deltaTime);