AddForce gets imprecise direction
Hi! I have problem with Rigidbody2D. When I use AddForce fireball is supposed to move towards an enemy, but it moves near or away from the enemy. And I can not figure out why.
private void MoveFireballTowardsEnemy(ref Vector3 attPos, ref Vector3 preyPosi) //attPos is not used yet
{
Debug.Log(preyPosi);
rb.AddForce(preyPosi); // at Start() this.rb = this.GetComponent<Rigidbody2D>();
// this.transform.position = Vector3.MoveTowards(this.transform.position, preyPosi, fireballSpeed); // This alternative code work as expected, but I want fireball to keep flying in sent direction, to not stop at enemy position so trying to get addforce to work
}
Function MoveFireballTowardsEnemy() is being called in the update. From the screenshot you can see that fighter gets enemy position correctly(minus rounding). Both fireball and enemy are parents. Fireball has dynamic rigidBody2D with all 0 properties except mass=1. Video shows how fireball works when I use alternative code
So... I tried to mess around about rigidbody component, layers, etc. nothing worked. What else should I look at? Or is there a another way to apply constant movement to object until it collides with smth?
Answer by xxmariofer · Jan 29, 2021 at 02:27 PM
If you are going deep into vectors you need to take a steep back and understand them, if you want the vector from Object A to Object B you need to do B - A, not simply vector B
rb.AddForce(preyPosi - this.transform.position);
also if you use forces, use the fixedupdate rather than the update
Thanks, this solution is acceptable. However my implementation does not work properly. Can you advise where I can read about vectors? Didn't find similar to yours info at documentation
Whats exactly happening? I dont really know good books or tutorials about vectors but there should be really a lot of information over the internet. take into account that with your solution the object A isnt trying to reach object B just adding a force in its direction, but once the object B moves, the object A continues having its force. I imagine you are looking for something like this
rb.velocity = preyPose - this.transform.position;
Imagine you have object A in point (1, 0) and object B in point (1,1) the direction from A to B is (0, 1) (its onlyready in the same X it just need to increment the y) or whats the same (1 - 1, 1 - 0)