簡體   English   中英

如何避免 Unity3d 中的代碼重復?

[英]How can I avoid code duplication in Unity3d?

我怎樣才能縮短這段代碼並避免復制,你有什么建議?

該方法用於使用按鈕在空間中移動相機

 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);

這樣就可以了,您可以刪除一些代碼行以適合您的游戲。 希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM