- Home /
How do I make an Enemy charge through a point?
Hi, I just have a quick question. I'm just finishing up the logic of a flying enemy that I have in my game and I need to know how would I tell the object to move towards and through the point I specified. That's pretty much it. I've used Vector2.MoveTowards, and tried setting the rigidbody's velocity to the point and it wouldn't say that it was a huge success... Because I want the enemy to have a ramming attack, I just think that I'm going about it slightly incorrectly...
Anyways here is my code (that pertains to my question):
private void LockOn()
{
targetPoint = new Vector2(target.transform.position.x, target.transform.position.y);
lockedOn = true;
}
if (lockedOn)
{
box.isTrigger = true;
rb.velocity = Vector2.MoveTowards(transform.position, targetPoint, speed / 25 * Time.deltaTime);
}
else if (!lockedOn)
{
LockOn();
}
Thanks in advance for any help!
Answer by Jon7e · Jun 26, 2020 at 08:08 AM
Create a directional vector from the starting position of the enemy to the player right after the enemy locked on. After the lock on just set the velocity equal to that vector times the speed. Generate the vector like this:
Vector2 direction = (targetPoint - transform.position).normalized
The ".normalized" sets the length of the vector to 1 so it becomes a direction.
Your answer
Follow this Question
Related Questions
2D endless scrolling game - Which method is best for moving objects without lags? 2 Answers
Bullet not moving from script 3 Answers
How do I create a vector that always points down locally 1 Answer
How do I make my character's movement less floaty? 1 Answer
AddForce or changing velocity affects only the Y Axis 1 Answer