using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowTouch : MonoBehaviour { private Vector3 initialPosition; void Start() { initialPosition = transform.position; } void Update() { if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position); touchPosition.z = 0f; transform.position = touchPosition; } float clampedX = Mathf.Clamp(transform.position.x, -5f, 5f); float clampedY = Mathf.Clamp(transform.position.y, -3f, 3f); transform.position = new Vector3(clampedX, clampedY, transform.position.z); } }上述代码运行后位置不对,拖动没有效果
时间: 2024-02-10 13:10:12 浏览: 173
根据你提供的代码,初步判断可能是因为物体的初始位置和拖动后的位置没有对齐导致的。你可以尝试在Update函数中添加一个判断条件,只有当触摸点触碰到物体时才继续执行拖动操作。修改后的代码如下:
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowTouch : MonoBehaviour
{
private Vector3 initialPosition;
void Start()
{
initialPosition = transform.position;
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
touchPosition.z = 0f;
// 判断触摸点是否在物体上
Collider2D collider = Physics2D.OverlapPoint(touchPosition);
if (collider != null && collider.gameObject == gameObject)
{
transform.position = touchPosition;
}
}
float clampedX = Mathf.Clamp(transform.position.x, -5f, 5f);
float clampedY = Mathf.Clamp(transform.position.y, -3f, 3f);
transform.position = new Vector3(clampedX, clampedY, transform.position.z);
}
}
```
另外,你还可以在Unity编辑器中检查物体的碰撞器组件是否已经添加,并且是否正确设置了碰撞器的形状和大小。
阅读全文