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.