我用C#做了一个第一人称脚本,用鼠标在一个单独的脚本中看。然而,在我的移动脚本中,基本的漫游功能可以工作,但是sprint函数不能。在对脚本进行更改后,我得出的结论是,它根本没有检测或使用编辑器中设置的sprint键的任何输入-尽管我可能是错的。脚本是:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed = 3.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
public float runSpeed = 6f;
public float crouchSpeed = 3f;
Vector3 moveDirection;
void Update() {
CharacterController controller = GetComponentInParent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
if (Input.GetButton("Jump")){
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) && Input.GetButton("Sprint")){
controller.Move (moveDirection * runSpeed * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)){
controller.Move (moveDirection * speed * Time.deltaTime);
}
}
}发布于 2015-05-28 21:32:19
这只是一个布尔逻辑错误:&&优先于||。
这条线路有问题:
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) && Input.GetButton("Sprint"))您应该将||条件包括在内:
if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) && Input.GetButton("Sprint"))无论如何,更好的方法是将这两部分分开:
if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
{
var realSpeed = Input.GetButton("Sprint") ? runSpeed : speed;
controller.Move (moveDirection * realSpeed * Time.deltaTime);
}发布于 2015-05-28 21:30:02
您应该在C# (https://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx)中检出运算符优先级
您遇到的问题是,如果按下W、S或A,代码将始终进入if语句的第一个条件。
要修复它,请使用括号将OR语句括起来,如下所示:
if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) && Input.GetButton("Sprint")){
controller.Move (moveDirection * runSpeed * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)){
controller.Move (moveDirection * speed * Time.deltaTime);
}https://stackoverflow.com/questions/30507632
复制相似问题