- Home /
Enemy Movement Problem!
Hello there,
Currently, what my script does is move the Enemy do a specific distance away from the player. What I want the Enemy to do is go to the minDist to the player, which would mean the distance between the player and the Enemy is for example "3f" I have a variable called "minDist" for that... How would I go and implement that?
This is part of the script where the Movement happens:
else
{
timeBetweenMoveCounter -= Time.deltaTime;
myRigidBody.velocity = Vector2.zero;
if (timeBetweenMoveCounter < 0f)
{
moving = true;
if (Vector3.Distance(transform.position, thePlayer.transform.position) <= maxDist)
{
timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeBetweenMove * 1.25f);
moveDirection = ((transform.position - thePlayer.transform.position).normalized) * (moveSpeed - 3);
}
}
}
All the Variables are floats in case that is important information. Thanks for any help I can get!
Answer by UnityNoob123 · Oct 22, 2017 at 07:28 AM
In the last line of code you should do something called a lerp, which will pick points between the start position and end position to travel to before ending at the end position. So doing something like:
Vector3 _newPos = transform.position + thePlayer.transform.position;
transform.position = Vector3.Lerp (transform.position - thePlayer.transform.position, _newPos, Time.deltaTime * speed);
So basically Vector3.Lerp takes three parameters, (startpos, endpos, %completion). The percent completion is also from 0 -1, so 1 is 100% done. So this should work, if it does not then we might have to make it into an Ienumerator function, but lets start with this.
Soooo... I fixed the problem differently I just had to replace "transform.position" with "moveDirection" but now another error appears and that is the $$anonymous$$Dist... This does not actually work. The Enemy seems to go further away from the player than what the value is... also it is now not implemented at the moment since I do not know where it would go.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Can't get smooth 2d movement for an object using transform.position 1 Answer
Distribute terrain in zones 3 Answers
Trying to stop enemies from clumping together. What am I doing wrong? 2 Answers
Is there a way to make a movement pattern using AnimationCurves? 0 Answers