在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(),但不知道如何实现它。
如果有人可以提供帮助,将不胜感激。
答案 0 :(得分:1)
由于此脚本将出现在场景中的每个对象上,因此您将需要有一个额外的变量并检查初始触摸是否与您的对象相交。
如果您正在使用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);
}
}