【发布时间】:2018-07-28 10:18:00
【问题描述】:
我为 2D 自上而下的 RPG 编写的移动代码有问题。请原谅我缺乏知识,但我最近才不得不学习如何编码,这是我第一次尝试运动控制。期望的结果是有两种输入法;控制器和键盘。我想让它们分开,所以当你使用控制器时,你不能使用键盘,反之亦然。这是代码。
using UnityEngine;
using System.Collections;
public class playerMovement : MonoBehaviour
{
public float Speed = 1;
private float deadZone = 0.25f;
// START - Use this for initialization
void Start () {}
// UPDATE is called once per frame - Using deadZone to compensate for faulty controllers etc.... Using options for controller true or false to switch between keyboard and controller input.
void FixedUpdate ()
{
Vector2 stickInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if ( Options.useController == true)
{
if( Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.A))
{
stickInput = Vector2.zero;
}
else if ( stickInput.magnitude < deadZone)
{
stickInput = Vector2.zero;
}
else
{
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
}
//Here is keyboard input - this is working great.
else if ( Options.useController == false)
{
if ( Input.GetKey(KeyCode.A) && Input.GetKey (KeyCode.W))
{
stickInput = new Vector2(-1f,1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.W) && Input.GetKey (KeyCode.D))
{
stickInput = new Vector2(1f,1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.S) && Input.GetKey (KeyCode.D))
{
stickInput = new Vector2(1f,-1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.A) && Input.GetKey (KeyCode.S))
{
stickInput = new Vector2(-1f,-1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.W))
{
stickInput = new Vector2(0f,1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.D))
{
stickInput = new Vector2(1f,0f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.S))
{
stickInput = new Vector2(0f,-1f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
else if ( Input.GetKey(KeyCode.A))
{
stickInput = new Vector2(-1f,0f);
stickInput.Normalize();
rigidbody2D.velocity = stickInput * Speed * Time.deltaTime;
}
}
}
}
在执行顶部循环时出现问题。当useController 等于真时,我希望键的移动为空。只要按住键,它就可以很好地工作,但是一旦您释放键(A、D、S、W),它就会退出 if 语句,并且播放器会被剩余的 GetAxis 值移动。
我必须使用GetAxis 作为此循环中的控制器输入,不幸的是 Unity 会自动从键中获取值。有没有办法不仅可以将速度限制为 0,还可以确保释放键时GetAxis 的值也变为 0。
【问题讨论】:
-
只是一个(非常快速的)建议:您是否尝试过使用 GetKeyDown() 而不是 GetKey()?顺便说一句,不知道这是否可以解决...
-
我也可以试试这个看看它是否改变了什么。在键下设置速度和 GetAxis 是有道理的。好主意!
-
很遗憾,这并没有解决问题,不过是个好主意!
标签: c# unity3d game-physics