Move RigiBody2d character to mouse (touch) position
Hello, I can move the player with a transform.position
but I'm trying to use RigidBody2D to calculate all movement so I can flipX when the player is going left or right.
I've got this code below, but the player simply teletransports to the mouse position, it doesn't move there.
public class MoveToMouse : MonoBehaviour {
public float moveSpeed = 5;
private Vector2 velocity;
private Vector2 mousePosition;
private SpriteRenderer sr;
private Rigidbody2D rb;
private Animator animator;
// Use this for initialization
void Start () {
mousePosition = transform.position;
velocity = new Vector2(moveSpeed, moveSpeed);
}
void Awake()
{
sr = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetMouseButtonDown(0)) {
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
//transform.position = Vector2.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
rb.MovePosition(mousePosition + velocity * Time.fixedDeltaTime);
// Note: This won't work because we are moving the player without Rigid Body velocity!
Debug.Log("Velocity x: " + rb.velocity.x);
if (rb.velocity.x <= 0)
{
sr.flipX = true;
}
else
{
sr.flipX = false;
}
//Debug.Log("position is" + transform.position);
}
}
If I use the commented transform.position
line it works, but I can't get tell whether the player is moving left or right because his velocity is always 0.
Maybe I should use transform.position
instead of RigidBody MovePosition
, but how do I determine whether the player is moving left or right? Right now, the player starts with a negative transform.position.x
. How can I tell if it's moving left or right from its last position?
Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220612190951im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rigidbody2D.MovePosition not working... 0 Answers
Kinematic 2D Rigidbody movement: Rigidbody2D.MovePosition vs Rigidbody2D.position problem 1 Answer
Ball bounces too much from AI collision 2 Answers
How to use Rigidbody2D.MovePosition to move a kinematic object around looping waypoints? 1 Answer
Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers