have an a object lup, i want to move it in some range of screen. Have code like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Touch2 : MonoBehaviour {
public float speed = 2.5F;
public GameObject lup;
public Text text;
float minX ,maxX, minY, maxY;
//private float minX, minY, maxX, maxY;
void Start(){
minX = Camera.main.ScreenToWorldPoint(new Vector2(0f, 0f)).x + 0.1f;
minY = Camera.main.ScreenToWorldPoint(new Vector2(0f, 0f)).y + 0.1f;
maxX = -minX;
maxY = -minX;
//lup.GetComponent<Renderer>().enabled = false;
}
public void Deffault(){
lup.transform.position = new Vector3(0, 0, 0);
}
public void Update(){
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
Touch touch = Input.GetTouch (0);
Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;
//text.text = "x:" + lup.transform.position.x.ToString () + " " + "y:" + lup.transform.position.y.ToString ();
if (lup.transform.position.x > minX / 1.39f && lup.transform.position.x < maxX / 1.41f) {
lup.GetComponent<Renderer> ().enabled = true;
//Vector3 pos = Input.mousePosition;
//transform.position = pos;
transform.Translate (touchDeltaPosition.x * speed, touchDeltaPosition.y, 0);
} else if (lup.transform.position.x < minX / 1.39f || lup.transform.position.x > maxX / 1.41f) {
transform.Translate (-touchDeltaPosition.x * speed + 0.5f, -touchDeltaPosition.y, 0);
}
}
if (Input.GetTouch (0).phase == TouchPhase.Ended) {
lup.GetComponent<Renderer>().enabled = false;
//lup.transform.position = new Vector3(minX*2.0f, maxY/1.5f, 0);
}
}
}
To move ojbect i use Touch and deltaPosition. minX,maxX is the range of screen. I want to move object if his position in range minX/1.39 and maxX/1.41. The problem is that if the object reaches the range it stops, and i added else if it reaches the range user move it in another side, but he still can move it out of range. How i can solve it?
//get delta
var delta = Input.GetTouch(0).deltaPosition;
//get position
var pos = lup.transform.position;
//add delta with clamp
pos.x = Mathf.Clamp(pos.x + delta.x, minX, maxX);
pos.y = Mathf.Clamp(pos.y + delta.y, minY, maxY);
//set pos
lup.transform.position = pos;