I started a new game project, and I have tried to find a way to only use a rigidbody2D
component to move my player game object instead of using transform.position
. And I can't come up with a good way to do it or find a tutorial or documentation about it.
I have got it to work with transform.position
, but how could I do it with rigidbody2D
?
CodePudding user response:
For movement with RigidBody2D you have mutiple options which are physics based. I assume that's the reason you want to use RigidBody2D in the first place.
RigidBody2D obj = GetComponent();
private void moveBody()
{
//direction towards your goal
Vector2D v = mousePosition - transform.position;
//Example 1 set the velocity
obj.velocity = v;
//Example 2 apply force
obj.AddForce(v, ForceMode2D.Impulse);
}
you can read more about RigidBody2D movement here
CodePudding user response:
You can throw an invisible collider on your stage and move your object to the position you want with the ray.
Ray ray;
public RaycastHit hit;
private void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
Debug.DrawRay(Camera.main.transform.position,hit.point);
transform.position = hit.point;
}
}
Best.