如何将此玩家移动脚本转换为触摸屏功能?

时间:2019-05-01 15:00:52

标签: c# unity3d

我有一个有效的玩家移动脚本,它是由自由角色控制器2D资产脚本和我自己编写的,它使用键盘的A和D键左右移动。

我想让此代码适用于触摸屏手机。基本上,您可以按屏幕左侧向左移动,而右侧则向右移动。

我还是C#的新手,可以使用帮助。

这是我当前的玩家移动脚本。

谢谢!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;

private Rigidbody2D m_Rigidbody2D;

private Vector3 m_Velocity = Vector3.zero;

public float runSpeed = 40f;

float horizontalMove = 0f;


private void Awake()
{
    m_Rigidbody2D = GetComponent<Rigidbody2D>();
}

public void Move(float move)
{
    // Move the character by finding the target velocity
    Vector3 targetVelocity = new Vector2(move * 10f, 
    m_Rigidbody2D.velocity.y);

    // And then smoothing it out and applying it to the character
    m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, 
targetVelocity, ref m_Velocity, m_MovementSmoothing);

}

// Update is called once per frame
void Update()
{

    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

}

void FixedUpdate()
{
    // Move our character
    Move(horizontalMove * Time.fixedDeltaTime);
}

}

1 个答案:

答案 0 :(得分:2)

有几种解决方案,但一种解决方案是使用Input API进行触摸:

void Update()
{
    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed; 

    for (int i = 0; i < Input.touchCount; ++i)
    {
        Touch touch = Input.GetTouch(i);
        bool touchIsOnRightSide = touch.position.x > Screen.width / 2;

        horizontalMove.x = runSpeed;
        if (!touchIsOnRightSide)
            horizontalMove.x *= -1;
    }

}

在此代码中,我们将遍历所有触摸,并通过检查触摸的X坐标是否大于或小于屏幕中间的X坐标来检查它们在右侧还是左侧。朝那个方向运动。