- Home /
Question by
TommyTheProgrammer · Jan 27, 2019 at 09:26 PM ·
mobiletouchmovement scriptdrag-and-droptouchphase
My dragging script "Sucks" all the other objects when touching it
My dragging script works well on one gameobject. However, when I drag an object around and touched another object, the other object will be dragged along! How to fix this problem?
Example: When I drag the selected tree around[Image 1] and touch another tree, the other tree will be "suck" into the selected tree, and be dragged along with the selected tree[Image 2].
[Image1]
[Image2]
Here's my script (dragged onto both of the trees): using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PutBuilding : MonoBehaviour
{
float timer = 0;
void Update()
{
if (Input.touchCount == 1)//if only one touch
{
if (timer < 1)//if holded for 1 second
{
if (Input.touches[0].phase == TouchPhase.Stationary)
{
timer += Time.deltaTime;
}
return;
}
if (Input.touches[0].phase == TouchPhase.Stationary)
{
return;
}
//Gets the world position of the mouse on the screen
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Checks whether the mouse is over the sprite
bool overSprite = this.GetComponent<SpriteRenderer>().bounds.Contains(mousePosition);
//If it's over the sprite
if (overSprite)
{
//If we've pressed down on the mouse (or touched on the iphone)
if (Input.GetButton("Fire1"))
{
//Set the position to the mouse position
this.transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
0.0f);
}
}
if (Input.touches[0].phase == TouchPhase.Ended)//Check if the dragging had ended
{
timer = 0;
}
}
}
}
unity-answers-drag-suck1.png
(153.7 kB)
unity-answers-drag-suck2.png
(154.5 kB)
Comment
Best Answer
Answer by tormentoarmagedoom · Jan 27, 2019 at 10:39 PM
Good day.
I think is easy to solve.
You only need to create some bool variable like "draggingSomething" to know if you are already dragging something. When you commence drag, this variable become false, and become true only when you drop the object.
BEfore drag an object, check if this bool avriable is true or false.
Bye!