【问题标题】:How do I convert this player movement script for touchscreen functionality?如何将此玩家移动脚本转换为触摸屏功能?
【发布时间】:2019-05-01 15:00:52
【问题描述】:

我有一个使用免费角色控制器 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);
}

}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    对此有多种解决方案,但一种解决方案可能是使用 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 坐标来检查它们是在右侧还是左侧,然后应用朝那个方向移动。

    【讨论】:

    • 我无法用言语来表达我现在有多开心!现在只是看到我的游戏在手机上运行,​​看看它的外观和感觉让我感觉非常好!非常感谢我的朋友
    • 啊,太棒了!这让我很高兴听到! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    相关资源
    最近更新 更多