使用手机触摸屏滑动



我是游戏开发新手,我正试图将我的代码更改为移动触摸。我试图改变流动的代码,使其适用于手机触摸屏,不幸的是失败了。你能帮我如何才能使流动的代码移动?代码如下:

Vector2 newPos;
bool canMove = true;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
newPos = transform.position;
}
private void Update()
{
if (canMove)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
newPos.x += 1.4f;
transform.position = newPos;                
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
newPos.x -= 1.4f;
transform.position = newPos;

}
}
if (Input.GetKeyDown(KeyCode.Space) && canMove)
{
rb.AddForce(Vector3.down * speed);
canMove = false;
}
Vector2 clampPos = transform.position;
clampPos.x = Mathf.Clamp(transform.position.x, -2.1f, 2.1f);
transform.position = clampPos;
}

创建一个Canvas,里面有一个屏幕宽的透明图像组件。

使用OnPointerDown和OnDrag事件函数来捕捉手指在图像上的移动。只需让你的类实现IPointerDownHandler和IDragHandler接口,并使用PointerEventData参数属性来获取delta或当前位置。

可以使用下面的代码。将其添加到屏幕宽图像中,并在检查器中分配您的Ridigbody2d和transform。

public class Movement: MonoBehaviour, IPointerDownHandler, IDragHandler
{
public Rigidbody2d rb;
public float maxSpeed = 10f;
public float sensitivity = 0.1f;
public float xBound = 2.1f;

Vector3 initialFingerPosition;
bool canMove = true;
public void OnPointerDown(PointerEventData pointerEventData)
{
initialFingerPosition = pointerEventData.position;
}
public void OnDrag(PointerEventData data)
{
if(!canMove)
return;
var position = rb.position;
position += data.delta * sensitivity * speed * Time.deltaTime;
position.x = Mathf.Clamp(position.x, -xBound, xBound);
rb.MovePosition(position);
}
}

最新更新