- Home /
Enemy walks through walls
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;
}
}
Please format your code on future posts. That way it is readable without me having to edit it.
Answer by MickM · Sep 11, 2012 at 01:11 AM
As above, you are setting the position directly which will override the physics.
note - http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-velocity.html
(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);
Answer by Piflik · Aug 26, 2012 at 09:35 PM
You are editing the transform directly. This will always ignore any collision. If you want collision, you have to use forces.
Your answer
Follow this Question
Related Questions
Help with Colliders? 0 Answers
How to use lookAt() while my character walking on a wall ? 0 Answers
Script for Car 2 Answers
Gun goes through walls (FPS) 1 Answer