如何避免 Unity3d 中的代码重复?

How can I avoid code duplication in Unity3d?

如何缩短此代码并避免复制,您有什么建议?

该方法用于在space中使用按钮

移动相机
 private void HandleMovementInput() {
        
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            new_position += (transform.forward * movement_speed);
        }

        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            new_position += (transform.forward * -movement_speed);
        }

        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            new_position += (transform.right * movement_speed);
        }

        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            new_position += (transform.right * -movement_speed);
        }

        
        if (Input.GetKey(KeyCode.Q))
        {
            new_rotation *= Quaternion.Euler(Vector3.up * rotation_amount);
        }

        if (Input.GetKey(KeyCode.E))
        {
            new_rotation *= Quaternion.Euler(Vector3.up * -rotation_amount);
        }
        //Shit code for zoom

        if (Input.GetKey(KeyCode.R))
        {
            new_zoom += zoom_amount;
        }

        if (Input.GetKey(KeyCode.F))
        {
            new_zoom -= zoom_amount;
        }

        transform.position = Vector3.Lerp(transform.position, new_position, Time.deltaTime * movement_time);
        transform.rotation = Quaternion.Lerp(transform.rotation, new_rotation, Time.deltaTime * movement_time);
        camera_transform.localPosition = Vector3.Lerp(camera_transform.localPosition,new_zoom, Time.deltaTime * movement_time); 
}

不幸的是,我的 Unity 不太好,无法解决这个架构案例。

尝试使用 Input.Getaxis。

https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

我将此代码用于我的玩家移动脚本

//playerinput is a Vector3 variable
playerinput = new Vector3(Input.GetAxis("Horizontal"), 0f, 
Input.GetAxis("Vertical"));
//transform.TransformDirection is here to move the player depending in their rotation
//playerinput.normalized is there for stopping strafing(for example, holding w and s together makes the player faster)
//I don't think you should change Mathf.Clamp01(playerinput.magnitude). This is very important for the movement to look good.
  Vector3 movevector = transform.TransformDirection(playerinput.normalized * Mathf.Clamp01(playerinput.magnitude)) * speed;
    
    //rb is the rigidbody by the way. Add rigidbody component to your camera
    rb.velocity = new Vector3(movevector.x, rb.velocity.y, movevector.z);

这样就可以了,您可以删除一些代码行以适合您的游戏。希望这对您有所帮助!