- Home /
How do I drag a sprite around?
I am working on a game which requires a ball to be clicked on, while the mouse button is down the ball should follow the mouse until the button is let go. The problem is when I try to click and drag the balls position translates off the screen instead of following the mouse's position; the ball moves on click. I have tried various methods to fixing it such as changing movement methods, clamping mouse position values, using world to screen point, but none of them have worked. Below is the code; using UnityEngine; using System.Collections;
public class Ball : MonoBehaviour {
//Sprite Renderer
private SpriteRenderer Sprite;
//Variables
private bool isPressed = false;
void Start()
{
//Intialisation
Sprite = gameObject.GetComponent<SpriteRenderer>();
ColourStart();
}
void Update()
{
Pressed();
}
void ColourStart()
{
float R = Random.Range(0.0f, 1.0f);
float G = Random.Range(0.0f, 1.0f);
float B = Random.Range(0.0f, 1.0f);
float A = 1.0f;
Sprite.color =new Color(R,G,B,A);
}
void OnMouseDown()
{
isPressed = true;
}
void OnMouseUp()
{
isPressed = false;
}
void Pressed()
{
if (isPressed)
{
Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
transform.Translate(mousePosition);
}
}
}
NOTE: The gameobject required to move is a sprite with rigidbody2D and 2D box colider. Thanks in advance.
Answer by NatCou · Jun 26, 2019 at 07:46 PM
This worked for me for dragging a game sprite in 2d space
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class dragGameSprite : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
Answer by Larry-Dietz · Jan 16, 2017 at 06:01 AM
I know this question is REALLY old, but here is the answer in case anyone else stumbles across this question.
In your If (isPressed) block, change your code to the following...
if (isPressed)
{
Vector2 MousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 objPosition = Camera.main.ScreenToWorldPoint(MousePosition);
transform.position = objPosition;
}
That should do what you are wanting.
-Larry