首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sprint不工作

Sprint不工作
EN

Stack Overflow用户
提问于 2015-05-28 21:13:37
回答 2查看 518关注 0票数 1

我用C#做了一个第一人称脚本,用鼠标在一个单独的脚本中看。然而,在我的移动脚本中,基本的漫游功能可以工作,但是sprint函数不能。在对脚本进行更改后,我得出的结论是,它根本没有检测或使用编辑器中设置的sprint键的任何输入-尽管我可能是错的。脚本是:

代码语言:javascript
复制
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);
    }

}
}
EN

回答 2

Stack Overflow用户

发布于 2015-05-28 21:32:19

这只是一个布尔逻辑错误:&&优先于||

这条线路有问题:

代码语言:javascript
复制
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) && Input.GetButton("Sprint"))

您应该将||条件包括在内:

代码语言:javascript
复制
if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) && Input.GetButton("Sprint"))

无论如何,更好的方法是将这两部分分开:

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 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语句括起来,如下所示:

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30507632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档