Drag the children of an empty game object in 2d, correctly
For my current project, I have a series of polyominoes (like the pieces of tetris) that are formed that some squares that are linked together by being parented to an empty game object. I need to drag each piece with the mouse. With my current code, I notice that wherever I click in the piece, the mouse pointer is always on top of the piece. What should I change in my code so that when I click, the mouse pointer keeps being on the same point of the piece?
//This is the script attached to the squares
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquareClickChild : MonoBehaviour {
public void OnMouseDown()
{
gameObject.transform.parent.GetComponent<SquareClick>().ParentOnMouseDown();
}
public void OnMouseUp()
{
gameObject.transform.parent.GetComponent<SquareClick>().ParentOnMouseUp();
}
}
//This is the script attached to their parent, the empty game object using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SquareClick : MonoBehaviour {
private Vector3 OriginalPosition;
private float Scale = 3.3f;
private bool dragging;
private float distance;
private void Start()
{
OriginalPosition = gameObject.transform.localPosition;
dragging = false;
}
public void ParentOnMouseDown()
{
gameObject.transform.localScale = new Vector3(Scale, Scale, gameObject.transform.localScale.z);
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
public void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
public void ParentOnMouseUp()
{
//The piece goes back to its original position, it works well so I won't post it here;
}
}
Your answer
Follow this Question
Related Questions
Drag & drop start position on a perspective camera? 0 Answers
[WebGL] UI drag in Edge browser 1 Answer
Collider not working properly 0 Answers
behaviour after shader 0 Answers