How to move the character and camera with the LR joystick like a 3D action game.
charaを動かす(左スティック)
- CharaControllerを使う。
- Unity - Scripting API: CharacterController.Moveを改造。
- Charaを進む方向は、カメラが向いている方向を使う。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharaController : MonoBehaviour { public Camera camera; public Vector3 camForward; public Transform cameraCon; public CharacterController controller; private Vector3 playerVelocity; private bool groundedPlayer; private float playerSpeed = 2.0f; private float jumpHeight = 5.0f; private float gravityValue = -9.81f; private void Start() { //controller = gameObject.G<CharacterController>(); } void Update() { groundedPlayer = controller.isGrounded; if (groundedPlayer && playerVelocity.y < 0) { playerVelocity.y = 0f; } //Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); Vector3 move = camera.transform.forward * Input.GetAxis("Vertical") + camera.transform.right * Input.GetAxis("Horizontal"); move.y=0; camForward=camera.transform.forward; controller.Move(move * Time.deltaTime * playerSpeed); if (move != Vector3.zero) { //gameObject.transform.forward = move; } // Changes the height position of the player.. if (Input.GetButtonDown("Jump")) //&& groundedPlayer) { playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue); } playerVelocity.y += gravityValue * Time.deltaTime; controller.Move(playerVelocity * Time.deltaTime); } }
カメラを動かす(右スティック)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CamOrbitControl : MonoBehaviour { public Camera camera; public Transform pivot; public float camSpeed=0.1f; private float _radX=0; private float _radY=0; public float amp = 1f; void Start() { } void Update() { _radX += Input.GetAxis("R_Stick_H") * camSpeed; _radY += -Input.GetAxis("R_Stick_V") * camSpeed; if(_radY>Mathf.PI/2f*0.9f)_radY=Mathf.PI/2f*0.9f; if(_radY<-Mathf.PI/2f*0.9f)_radY=Mathf.PI/2f*0.9f; var xx = amp * Mathf.Sin( _radX) * Mathf.Cos( _radY ); var yy = amp * Mathf.Sin( _radY ); var zz = amp * Mathf.Cos( _radX ) * Mathf.Cos( _radY ); camera.transform.localPosition = new Vector3(xx,yy,zz); camera.transform.LookAt(pivot,Vector3.up); } }
※ Macを使っててPSコントローラーを使った。InputManagerでR_Stick_H,R_Stick_Vを設定した。