- Home /
addForce to Character in direction of other object
I have a character (the little, green, slimy thing on the attached picture) and an arrow that rotates between up and right. At the tip of the arrow, there's an Object called "arrow_tip" which I want to use to tell my Character in which direction the character should fly.
I want to do this with addforce as it's triggered once by a mouse click.
How do I tell the character to add force in the direction of the "arrow_tip" object?
I have tried the following:
if (Input.GetMouseButtonDown(0)
{
direction = new Vector2(arrow_tip.transform.position.x * strength, arrow_tip.transform.position.y *
strength);
rb.AddForce(direction);
}
where - arrow_tip is the arrow_tip object (via a Serialized Field) - strength is a float value between 0 and 10
Help is appreciated, if you need more information just tell me :)
If you subtract the arrow base coordinates from the tip coordinates, you get a vector that starts from the base of the arrow and looks towards the tip.
direction = new Vector2(arrow_tip.transform.position.x - arrow_base.transform.position.x, arrow_tip.transform.position.y - arrow_base.transform.position.y) * strength;
Answer by blinkafrootable · May 25, 2020 at 04:42 AM
If you subtract your "destination" vector (the arrow tip) by your "start" vector (the base of the arrow), you'll get a vector that points in the direction of the destination from the start. However, you want to normalize that vector (make it so that its magnitude/size is no larger than 1 unit) because, otherwise, the distance from the "start" to the "destination" vectors will impact the amount of force added. This can be expressed using the following code:
direction = (arrow_tip.transform.position - transform.position).normalized;
rb.AddForce(direction * strength);
This worked, thanks! The only thing I had to change was to add rb.AddForce(direction * strength * 1000)
as strength itself is a very low value I guess.