代码之家  ›  专栏  ›  技术社区  ›  Gabriele Conserva

玩家输入在统一中无法正常工作

  •  0
  • Gabriele Conserva  · 技术社区  · 2 年前

    我试图重现《艾萨克在团结中的束缚》的各个方面(只是作为一种学习练习,而不是整个游戏)。我已经创建了一个脚本,使Isaac能够使用WASD键移动,并使用箭头键射出眼泪。虽然WASD的移动效果很好,但按下箭头键会使Isaac同时移动和射击。理想情况下,箭头键只能用来发射眼泪,而不能移动艾萨克。我正在寻求帮助来解决这个问题。如果这是一个简单的问题,请道歉,并为糟糕的英语感到抱歉

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class IsaacMovements : MonoBehaviour
    {
        public float speed = 40f;
        public Rigidbody2D projectilePrefab;
        public float projectileSpeed = 10f;
    
        private Rigidbody2D rb;
    
        // Start is called before the first frame update
        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
            if (rb == null)
            {
                Debug.LogError("Rigidbody2D component is not attached to the GameObject.");
            }
        }
    
        // Update is called once per frame
        void Update()
        {
            Move();
    
            if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow) ||
                Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow))
            {
                Shoot();
            }
        }
    
        void Move()
        {
            float horizontalInput = Input.GetAxisRaw("Horizontal");
            float verticalInput = Input.GetAxisRaw("Vertical");
    
            Vector2 movement = new Vector2(horizontalInput, verticalInput).normalized;
            rb.velocity = movement * speed;
        }
    
        void Shoot()
        {
            if (Input.GetKey(KeyCode.LeftArrow))
                Fire(Vector2.left);
            else if (Input.GetKey(KeyCode.RightArrow))
                Fire(Vector2.right);
            else if (Input.GetKey(KeyCode.UpArrow))
                Fire(Vector2.up);
            else if (Input.GetKey(KeyCode.DownArrow))
                Fire(Vector2.down);
        }
    
        void Fire(Vector2 direction)
        {
            Rigidbody2D projectileInstance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
            projectileInstance.velocity = direction * projectileSpeed;
        }
    }
    

    我试着在整个过程中广泛地更改代码,但似乎什么都不起作用。我还试着用不同的键代替箭头键进行射击,但仍然没有得到想要的结果。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Shir Cohen    2 年前

    发生这种情况是因为您正在使用 输入GetAxisRaw(“水平”) ,在Unity编辑器中,横轴定义为A、D和左右键,有几个解决方案,其中两个最简单的是:

    1. 更改GetAxisRaw,为每个方向使用所需的特定键(这是一种惰性解决方案)

    2. 在编辑器首选项中,在编辑处将轴关键点更改为您想要的任意关键点>项目设置>输入管理器>轴>水平/垂直>按钮+Alt按钮