c# - 在范围区域内移动对象 Unity
问题描述
有一个对象 lup,我想在屏幕的某个范围内移动它。有这样的代码
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);
}
}
}
要移动对象,我使用 Touch 和 deltaPosition。minX,maxX 是屏幕的范围。如果他的位置在 minX/1.39 和 maxX/1.41 范围内,我想移动对象。问题是,如果对象达到它停止的范围,我添加了 else 如果它达到范围用户将它移到另一侧,但他仍然可以将它移出范围。我该如何解决?
解决方案
//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;
推荐阅读
- html - 如何制作循环背景元素?
- android - 像图像中一样自定义 GridView
- facebook-graph-api - 如何使用新的 Instagram Graph 或 Basic Display API 获取普通用户的个人资料图片(截至 2020 年 6 月 29 日)
- python - 无法在 Python 多处理中获取参数
- ansible - Ansible Connection 被远程主机关闭以获取长时间运行的模块
- java - _setmode( _fileno(stdin), _O_BINARY) 在使用 /MD 编译时等待 Enter 键
- reactjs - React Native with TypeScript Error无法解析模块
- oracle - 如何从存储在 clob 列中的 url 中提取值
- linux - 为什么詹金斯不能在 docker 容器中使用 DNS?
- python - 如何使用 python 创建 struct c 并在套接字上发送