- Home /
Move 2D Sprite Horizontally With Mouse
I'm a total noob with game development and Unity.
I have a script for moving my 2D sprite horizontally with the mouse. My problem is that my sprite isn't at the same X position as my mouse pointer. For example, my pointer would be in the middle of the screen and my sprite would be to the far right. I want both to be at the same X position at all times.
I've looked at some similar posts and one answer referred to using Camera.ScreenToWorldPoint to convert the mouse position to world coordinates. After looking at the documentation, I don't really understand how to use Camera.ScreenToWorldPoint.
I would really like some help because I've been stuck on this problem for 2 weeks now.
My script:
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
Vector2 pos = transform.position;
pos.x = Input.mousePosition.x + transform.position.x;
rb.MovePosition(pos * movementSpeed * Time.fixedDeltaTime);
}
Answer by alph1 · Apr 28, 2017 at 10:22 AM
Use Camera.ScreenToWorldPoint as Camera.main.ScreenToWorldPoint(Input.mousePosition)
if you want both to be at the same x position at all times then you dont need a rigidbody Component to achieve that,what you need is -> this.transform.position = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,this.transform.position.y);
using this code your sprite will fixed the initial y position but its x position will be same as your mousePosition of the screen.