Rigidbody follow player and maintain all physical properties
I created a simple script that allowed one Rigidbody object (AI/Enemy) to smoothly chase after the Rigidbody player. However, it has one problem; the 'Enemy' is able to push the player across the screen with no regard for physics, and the player is powerless to push back, not matter how much force is applied.
Current AI/'Enemy' script:
#pragma strict
var rb2D: Rigidbody2D;
var player : GameObject;
var playerPOS : Vector2;
var followVector : Vector2;
var selfPOS : Vector2;
function Start ()
{
rb2D = GetComponent.<Rigidbody2D>();
player = GameObject.Find("CellPlayer");
}
function FixedUpdate () {
playerPOS = player.transform.position;
selfPOS = transform.position;
followVector = Vector2.MoveTowards(selfPOS, playerPOS, 0.06);
rb2D.MovePosition(followVector);
}
The player's Rigidbody is moved using AddForce, which allows other forces to act against it, such as drag and collisions. However, my current method of moving the 'Enemy' requires MovePosition, which appears to ignore weight, drag, collisions, and basically all other forces.
I tried several ways to have the 'Enemy' follow the player through AddForce, but getting it to work to the point where it's smooth and reliable seems overly complicated.
Is there another form of movement that I missed that allows you to tell a Rigidbody object to move (or attempt moving) to a vector while preserving its physical properties? Or is there an easier way to accomplish this with AddForce?
Edit: This is for a 2D game on Unity 5.3.
Answer by Trigary · Jan 30, 2016 at 01:57 PM
MovePosition basically teleports the objects, don't use it if you want physics to work.
The other way is to use velocity vectors: [rigidbody2D].velocity = Vector2
In a top-down game you could do: EnemyRigidbody.velocity = transform.up * speed.y;
Thank you for your answer! Unfortunately, velocity = Vector2
seems to work in a similar fashion to AddForce(Vector2)
, as in it continually applies force in a direction relative to itself, rather than towards a vector point on the map. To achieve following the player, I require either a method that allows adding force or velocity towards a vector point on the map, or a way to deter$$anonymous$$e the player's direction and distance from the 'Enemy' and then somehow transform that into an appropriate vector for AddForce or velocity.
See the answer to this question: http://answers.unity3d.com/questions/954939/using-direction-and-rigidbody2daddforce-to-move-to.html