【发布时间】:2018-01-17 15:13:46
【问题描述】:
我想要做的是当用户触摸一个对象时,他可以移动它,特别是在屏幕上用多点触控手指
我也试过用鼠标点击这个射线,但还是有同样的问题
为此,我在更新时使用此代码
public LayerMask touchInputMask;
private static List<GameObject> touchList = new List<GameObject>();
public static Dictionary<int, objectst> touchobjects = new
Dictionary<int, objectst>();
private GameObject[] touchesOld;
private RaycastHit hit;
public GUIText Count, IndexLift;
private Vector3 targetPos;
public struct objectst { public Vector3 screenPoint; public Vector3 offset;
}
void Update(){
if (nbTouches > 0)
{
//nbTouches = 5;
//print(nbTouches + " touch(es) detected");
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
for (int i = 0; i < nbTouches; i++)
{
Touch touch = Input.GetTouch(i);
//print("Touch index " + touch.fingerId + " detected at
position " + touch.position);
Ray ray = Camera.main.ScreenPointToRay(touch.position);
if (Physics.Raycast(ray, out hit,Mathf.Infinity,
touchInputMask))
{
GameObject recipient = hit.transform.gameObject;
print("#### touch hit name object "+recipient.name);
touchList.Add(recipient);
//recipient.;
if (touch.phase == TouchPhase.Began)
{
print("#### tcouh begin");
objectst tempobj = new objectst();
tempobj.screenPoint =
Camera.main.WorldToScreenPoint(recipient.transform.position);
tempobj.offset = recipient.transform.position -
Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x,
touch.position.y, tempobj.screenPoint.z));
touchobjects.Add(touch.fingerId, tempobj);
}
if (touch.phase == TouchPhase.Stationary || touch.phase
== TouchPhase.Moved)
{
print("#### tcouh stationary or moved");
Vector3 curScreenPoint = new Vector3(touch.position.x, touch.position.y,
touchobjects[touch.fingerId].screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + touchobjects[touch.fingerId].offset;
print("#### objet doit être deplacer x = "+curPosition.x+"y = "+curPosition.y);
recipient.transform.position = curPosition;
}
if (touch.phase == TouchPhase.Ended)
{
print("#### tcouh ended");
Vector3 curScreenPoint = new Vector3(touch.position.x, touch.position.y,
touchobjects[touch.fingerId].screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) - touchobjects[touch.fingerId].offset;
recipient.transform.position = curPosition;
}
}
}
}
}
编辑
屏幕截图
【问题讨论】:
-
您尝试触摸的对象是否有碰撞器?
-
您还可以附上您的图层蒙版的屏幕截图吗?你确定你的对象在那个层上吗?
-
我只是添加一个屏幕截图
-
@Eddge 是的,我有一个rigidbody2d,脚本附加到我想移动的这个对象上,所以我想在同一层?
-
另一个需要注意的关键点,你的使用
physics.raycast所以你的对撞机需要是一个 3d 对撞机,要对 2d 对撞机进行射线投射,你需要使用physics2d.raycast
标签: c# unity3d raycasting