- Home /
Enemy flying issue
I'm making a 2D side scroller. In an enemy I put this code:
var distance; var target : Transform;
var lookAtDistance = 5.0; var attackRange = 10.0; var moveSpeed = 5.0; var damping = 6.0; private var isItAttacking = false;
function Update ()
{
distance = Vector3.Distance(target.position, transform.position);
if(distance < lookAtDistance)
{
isItAttacking = false;
renderer.material.color = Color.yellow;
lookAt ();
}
if(distance > lookAtDistance)
{
renderer.material.color = Color.green;
}
if(distance < attackRange)
{
attack ();
}
if(isItAttacking)
{
renderer.material.color = Color.red;
}
}
function lookAt () { var rotation = Quaternion.LookRotation(target.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); }
function attack () { isItAttacking = true; renderer.material.color = Color.red;
transform.Translate(Vector3.forward * moveSpeed *Time.deltaTime);
}
When I get close to my enemy, he chases me and flies all around the stage (while chasing me). Is there any way to add gravity to him, because I even put a rigid-body component on him.
Many thanks, David
Answer by nasapc123 · Feb 27, 2012 at 01:07 AM
basically by using transform.Translate you are directly moving the object in question. instead you would want to clamp it so that he only follows your x and z position, so that he sticks to the ground and is only translated along the flat plane, not up. you would then be free to add jumping AI code for him, and the transform.Translate command wouldnt be taking over where gravity should.
transform.Translate.x(Vector3.forward * moveSpeed *Time.deltaTime,0,0);
Your answer
Follow this Question
Related Questions
Adding a jump feature help? 2 Answers
Getting this character controll script working right 1 Answer
how to add gravity to this script 2 Answers