我怎樣才能縮短這段代碼并避免復制,你有什么建議?
該方法用于使用按鈕在空間中移動相機
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 中解決這個架構案例的能力并不強)
uj5u.com熱心網友回復:
嘗試使用 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);
這可以解決問題,您可以洗掉一些代碼行以適應您的游戲。希望這有幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461619.html
