好的,所以我试图让玩家按Shift + W而不是W时产生不同的玩家动画和速度。
这是W的工作代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MherControls : MonoBehaviour
{
float speed = 2;
float rotSpeed = 80;
float rot = 0f; //0 when we start the game
float gravity = 8;
Vector3 moveDir = Vector3.zero;
CharacterController controller;
Animator anim;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//anim condition 0 = idle, 1 = walk, 2 = run
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.W))
{
anim.SetInteger("condition", 1); //changes condition in Animator Controller to 1
moveDir = new Vector3(0, 0, 1); //only move on the zed axis
moveDir *= speed;
moveDir = transform.TransformDirection(moveDir);
if (speed < 10){
speed += Time.deltaTime; //max speed is 10
//Debug.Log(speed);
}
if (speed >= 2.5)
{
anim.SetInteger("condition", 2);
}
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetInteger("condition", 0);
speed = 2;
moveDir = new Vector3(0, 0, 0);
}
rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime; //horizontal are A and D keys and also left and right arrows
transform.eulerAngles = new Vector3(0, rot, 0); //our character's transform property
}
//every frame move player on y axis by 8. so lowering to the ground
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime);
}
}
但是,当我尝试介绍Shift + W行为时,例如:
if ( (Input.GetKey(KeyCode.W)) && (Input.GetKeyDown(KeyCode.LeftShift)) {
speed = 2;
anim.SetInteger("condition", 1);
}
然后它不起作用。它只是一直进入W分支,从不让我为Shift + W专门编码行为。
我在做什么错?当播放器按住Shift + W时,与播放器仅按住W时,我该如何做出不同的行为?
答案 0 :(得分:1)
您需要切换检查密钥的方式。 GetKeyDown仅适用于您按下键(https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html)的帧,而按住键(https://docs.unity3d.com/ScriptReference/Input.GetKey.html)时GetKey仍为true。因此,要按住shift键,然后按W键,检查应该是
if ( (Input.GetKey(KeyCode.LeftShift)) && (Input.GetKeyDown(KeyCode.W)) {
speed = 2;
anim.SetInteger("condition", 1);
}