RouXin096 2021-11-02 16:06 采纳率: 0%
浏览 39

写的代码小键盘上下左右正常,WASD出问题

一开始W可以用S用不了,点了AD以后WS都用不了,只能左右动

public float horizontal = 0f;
public float vertical = 0f;
public float speed = 2f;
public Vector3 direction = new Vector3(0, 1, 0);
public bool isVerticalAvailable = false;
private Vector3 playerRotation = Vector3.zero;
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    //1 通过键盘按钮按下以及松开,来获取水平/垂直方向的可用性
    if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.UpArrow))
    {
        isVerticalAvailable = true ;
    }
    if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
    {
        isVerticalAvailable = false ;
    }
    if (Input.GetKeyUp(KeyCode.DownArrow) || Input.GetKeyUp(KeyCode.UpArrow))
    {
        isVerticalAvailable = false ;
    }
    if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
    {
        isVerticalAvailable = true ;
    }
    //通过Input控制器判断方向
    horizontal = Input.GetAxisRaw("Horizontal");
    vertical = Input.GetAxisRaw("Vertical");
    //垂直方向
    if (isVerticalAvailable) 
    {
        if (vertical > 0) //上
        {
            playerRotation = Vector3.zero;
        }
        if (vertical < 0) //下
        {
            playerRotation = new Vector3(0,0,180);
        }
    }
    //水平方向
    if (!isVerticalAvailable)
    {
        if (horizontal > 0) //右
        {
            playerRotation = new Vector3(0, 0, -90);
        }
        if (horizontal < 0) //左
        {
            playerRotation = new Vector3(0, 0, 90);
        }
    }
    //重置游戏方向
    this.transform.rotation = Quaternion.Euler(playerRotation);
    if (horizontal!=0 || vertical!=0) 
    {
        this.transform.Translate(direction * speed * Time.deltaTime);
    }
}
  • 写回答

2条回答 默认 最新

  • 也曾想仰望星空 2021-11-03 10:11
    关注

    你这写的好乱啊

            if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) //前移
            {
                transform.Translate(Vector3.forward * speed * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) //后移
            {
                transform.Translate(Vector3.back * speed * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) //左移
            {
                transform.Translate(Vector3.left * speed * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) //右移
            {
                transform.Translate(Vector3.right * speed * Time.deltaTime);
            }
    

    或者

            horizontal = Input.GetAxisRaw("Horizontal");
            vertical = Input.GetAxisRaw("Vertical");
    
            if(horizontal!=0 || vertical!=0)
            {
                transform.Translate(new Vector3(horizontal,0,vertical) * speed * Time.deltaTime);
            }
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月2日