我是游戏开发的新手。我正在努力使自己起来。不幸的是,我试图更改当前代码以使其可用于移动触摸屏。您能帮我怎样为手机制作流畅的代码?
private Vector2 mousePos;
private Rigidbody2D rb;
private Vector2 offsetClicked;
private Vector2 offsetReleased;
private void Start () {
rb = GetComponent<Rigidbody2D> ();
offsetReleased = transform.position;
}
private void FixedUpdate () {
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
if (Input.GetMouseButton (0)) {
Vector2 newPos = new Vector2 (
Mathf.Clamp(mousePos.x + offsetClicked.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
mousePos.y + offsetClicked.y
);
rb.MovePosition (newPos);
offsetReleased = newPos - (Vector2) Camera.main.transform.position;
} //Clicked
else {
Vector2 newPos = new Vector2 (
Mathf.Clamp (Camera.main.transform.position.x + offsetReleased.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
Camera.main.transform.position.y + offsetReleased.y
);
rb.MovePosition (newPos);
offsetClicked = newPos - mousePos;
} //Released
}
以上适用于鼠标的代码。
答案 0 :(得分:0)
而不是检查是否单击了鼠标按钮,而是检查是否存在任何触摸,然后提取触摸位置。 Input.touches
返回上一帧的触摸列表,因此您可以使用它来找到将替换mousePos
在代码中的触摸的位置。
Touch myTouch;
Vector2 myTouchPosition;
Update()
{
if (Input.touchCount > 0)
{
myTouch = Input.touches[0]; //Get the first touch
myTouchPosition = Camera.main.ScreenToWorldPoint(myTouch.position);
}
}
此外,您可以使用touch phases来确定触摸期间您希望发生什么事情。
答案 1 :(得分:0)
将CrossPlatformInput
包中的内容导入到您的项目中,您实际上可以继续使用Input.GetMouseButton(xxx)。
using UnityEngine;
using CrossPlatformInput;
public class MyClass : MonoBehaviour {
private Vector2 mousePos;
private Rigidbody2D rb;
private Vector2 offsetClicked;
private Vector2 offsetReleased;
private void Start () {
rb = GetComponent<Rigidbody2D> ();
offsetReleased = transform.position;
}
private void FixedUpdate () {
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
if (Input.GetMouseButton (0)) {
Vector2 newPos = new Vector2 (
Mathf.Clamp(mousePos.x + offsetClicked.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
mousePos.y + offsetClicked.y
);
rb.MovePosition (newPos);
offsetReleased = newPos - (Vector2) Camera.main.transform.position;
} //Clicked
else {
Vector2 newPos = new Vector2 (
Mathf.Clamp (Camera.main.transform.position.x + offsetReleased.x, GameManager.gm.cameraEdges.w + 0.32f, GameManager.gm.cameraEdges.y - 0.32f),
Camera.main.transform.position.y + offsetReleased.y
);
rb.MovePosition (newPos);
offsetClicked = newPos - mousePos;
} //Released
}
}
(请参见此处:https://docs.unity3d.com/Manual/CrossPlatformConsiderations.html)
触摸并点击
Input.GetMouseButtonXXX函数的设计使其具有一个 即使在移动设备上也有相当明显的解释 本身不是“鼠标”。屏幕上的单次触摸报告为 左键单击,Input.mousePosition属性给出位置 只要手指触摸屏幕就可以触摸。这表示 简单鼠标交互的游戏通常可以透明地运行 在台式机和移动平台之间。当然, 转换通常比这简单得多。台式机 游戏可以使用多个鼠标按钮,而手机游戏可以 一次检测屏幕上的多个触摸。