unity3d - 在 Unity 中检测对特定对象的触摸
问题描述
在 Unity 2D 中开发 Android 游戏。长话短说,我在场景中有两个单独的对象,上面附有这个脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeScript : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
public static int brojbacanja=0;
public static bool bacenaprva = false;
[Range (0.05f, 1f)]
public float throwForce = 0.3f;
void Update(){
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && brojbacanja == 0) {
touchTimeStart = Time.time;
startPos = Input.GetTouch (0).position;
}
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended && brojbacanja == 0) {
touchTimeFinish = Time.time;
timeInterval = touchTimeFinish - touchTimeStart;
endPos = Input.GetTouch (0).position;
direction = startPos - endPos;
GetComponent<Rigidbody2D> ().AddForce (-direction / timeInterval * throwForce);
brojbacanja = 1;
bacenaprva = true;
}
}
}
这样做几乎可以让我在屏幕上的任何位置滑动并抛出它所附着的对象。因为我有两个不同的物体要分开扔,所以我想稍微改变一下,所以当我触摸要扔的物体时,另一个保持不动。我已经阅读过这个问题并尝试使用 Raycast 和 OnMouseDown() 但不知道如何实现它。
如果有人可以提供帮助,将不胜感激。
解决方案
由于此脚本将在场景中的每个对象上,您将需要一个额外的变量并检查初始触摸是否与您的对象相交。
如果您使用的是 3D 对象(我假设这是因为您提到了光线追踪),那么您将需要将屏幕上的触摸位置转换为光线的东西,然后您将其投射以查看它是否与您的对象相交。你的对象必须有碰撞才能工作。
public class SwipeScript : MonoBehaviour
{
// added these two values, set the coll value to your collider on this object.
bool isTouching;
public Collider coll;
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
public static int brojbacanja=0;
public static bool bacenaprva = false;
[Range (0.05f, 1f)]
public float throwForce = 0.3f;
void Update(){
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && brojbacanja == 0) {
if(IsTouchOverThisObject(Input.GetTouch(0))) {
isTouching = true;
touchTimeStart = Time.time;
startPos = Input.GetTouch (0).position;
}
}
if (isTouching && Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended && brojbacanja == 0) {
isTouching = false;
touchTimeFinish = Time.time;
timeInterval = touchTimeFinish - touchTimeStart;
endPos = Input.GetTouch (0).position;
direction = startPos - endPos;
GetComponent<Rigidbody2D> ().AddForce (-direction / timeInterval * throwForce);
brojbacanja = 1;
bacenaprva = true;
}
}
bool IsTouchOverThisObject(Touch touch) {
Ray ray = Camera.main.ScreenPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
RaycastHit hit;
// you may need to adjust the max distance paramter here based on your
// scene size/scale.
return coll.Raycast(ray, out hit, 1000.0f);
}
}
推荐阅读
- python - 来自 TCP/IP Python 的图像数据
- python - 唤醒词检测中的误报过多
- c# - 在 C# 中使用单独的单元格将 2D 数组保存到 csv
- javascript - 如何使用 $.post 调用 javascript 函数并使用初始页面的 css 获取 html 数据
- javascript - 异步函数不等待 Node.js 中子进程的结果
- c++ - C++:如何编写一个函数来检查用户输入的数字是否在数组中?
- amazon-web-services - 在亚马逊工作区和本地机器之间切换的键盘快捷键?
- html - 遍历 Jquery 循环中的每个属性
- python - 已解决:Django:删除请求返回错误 405
- java - 如何在不使用事件侦听器的情况下从 Firestore 文档中获取单个字段?