Lni*_*tus 28 c# click touch unity-game-engine
我想在我的gameObject 2D上检测点击/触摸事件.
这是我的代码:
void Update()
{
if (Input.touchCount > 0)
{
Debug.Log("Touch");
}
}
Run Code Online (Sandbox Code Playgroud)
Debug.Log("Touch");
当我点击屏幕或我的gameObject时没有显示.
naX*_*aXa 31
简短的回答:是的,触摸可以处理Input.GetMouseButtonDown()
.
Input.GetMouseButtonDown()
,Input.mousePosition
和相关的功能在触摸屏上作为点击工作(这有点奇怪,但欢迎).如果您没有多点触控游戏,这是保持编辑器内游戏运行良好同时仍保持设备触摸输入的好方法.(来源:Unity社区)
可以通过Input.simulateMouseWithTouches
选项启用/禁用带触摸的鼠标模拟.默认情况下,此选项已启用.
虽然它有利于测试,但我认为Input.GetTouch()
应该在生产代码中使用.
有趣的方法是为OnMouseUp()
/ OnMouseDown()
event 添加触摸处理:
// OnTouchDown.cs
// Allows "OnMouseDown()" events to work on the iPhone.
// Attach to the main camera.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class OnTouchDown : MonoBehaviour {
void Update () {
// Code for OnMouseDown in the iPhone. Unquote to test.
RaycastHit hit = new RaycastHit();
for (int i = 0; i < Input.touchCount; ++i)
if (Input.GetTouch(i).phase.Equals(TouchPhase.Began)) {
// Construct a ray from the current touch coordinates
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray, out hit))
hit.transform.gameObject.SendMessage("OnMouseDown");
}
}
}
Run Code Online (Sandbox Code Playgroud)
(来源:Unity Answers)
UPD:有统一的远程模拟在编辑模式触碰(使用Unity编辑器4和Unity编辑器的5部作品)移动应用程序.
sda*_*bet 18
根据我的理解,Unity播放器不允许您触发触摸事件,只触发鼠标事件.
但您可以根据鼠标事件模拟假触摸事件,如本博文中所述:http://2sa-studio.blogspot.com/2015/01/simulating-touch-events-from-mouse.html
void Update () {
// Handle native touch events
foreach (Touch touch in Input.touches) {
HandleTouch(touch.fingerId, Camera.main.ScreenToWorldPoint(touch.position), touch.phase);
}
// Simulate touch events from mouse events
if (Input.touchCount == 0) {
if (Input.GetMouseButtonDown(0) ) {
HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Began);
}
if (Input.GetMouseButton(0) ) {
HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Moved);
}
if (Input.GetMouseButtonUp(0) ) {
HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Ended);
}
}
}
private void HandleTouch(int touchFingerId, Vector3 touchPosition, TouchPhase touchPhase) {
switch (touchPhase) {
case TouchPhase.Began:
// TODO
break;
case TouchPhase.Moved:
// TODO
break;
case TouchPhase.Ended:
// TODO
break;
}
}
Run Code Online (Sandbox Code Playgroud)