カメラとプレイヤーの移動と回転。
カメラはプレイヤーの子オブジェクトとして書いた。
たぶんMinecraft式?
Twitter:@ritz_prgrm
おかしなところとかあったらTwitterで教えて欲しいです(ブログで書くのはめんどうだと思うので)
プレイヤー(RigidBodyのアタッチがいる)
public RigidBody rigidBody;
public Camera PlayerCamera;
private void Awake()
{
if (rigidBody == null)
{
rigidBody = GetComponentInParent();
}
if(PlayerCamera == null)
{
PlayerCamera = GetComponentInChildren();
}
}
void Update()
{
inputHorizontal = Input.GetAxisRaw("Horizontal");
inputVertical = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
// カメラの方向からXZ平面の単位ベクトルを取得
// Vector.ScaleのVector b(new Vector3(1,0,1))の部分でyをゼロにすることでXZの単位ベクトルを取得している。
// normalizedが単位ベクトルにしている。
Vector3 cameraForward = Vector3.Scale(PlayerCamera.transform.forward, new Vector3(1, 0, 1)).normalized;
Vector3 cameraSide = Vector3.Scale(PlayerCamera.transform.right, new Vector3(1, 0, 1)).normalized;
// 縦移動の数値
Vector3 moveForward = cameraForward * inputVertical;
// 横移動の数値
Vector3 moveSide = cameraSide * inputHorizontal;
//縦と横移動をまとめてやってる
rigidBody.velocity = (moveForward + moveSide) * moveSpeed + new Vector3(0, rigidBody.velocity.y, 0);
// 向きを常に一定にしたい
if (moveForward != Vector3.zero && inputVertical > 0)
{
//前に進むとき
transform.rotation = Quaternion.LookRotation(moveForward);
}else if(moveForward != Vector3.zero && inputVertical < 0)
{
//後ろに進むとき
transform.rotation = Quaternion.LookRotation(-moveForward);
}
if (moveSide != Vector3.zero)
{
//左右に進むとき
transform.rotation = Quaternion.LookRotation(cameraForward);
}
}プレイヤーカメラ(カメラにアタッチする)
public Transform VerticalRotation;
public Transform HorizontalRotation;
public float XRotation;
public float YRotation;
private void Awake()
{
if(VerticalRotation == null)
{
//PlayerCameraはPlayerの子供
VerticalRotation = transform.parent;
}
if(HorizontalRotation == null)
{
HorizontalRotation = GetComponent();
}
}
void Update()
{
XRotation = Input.GetAxis("Mouse X");
YRotation = Input.GetAxis("Mouse Y");
//ここをマイナスにするとマウスの上下と逆にカメラワークが動く
VerticalRotation.transform.Rotate(0, XRotation, 0);
//ここをプラスにするとマウスの左右と逆にカメラワークが動く
HorizontalRotation.transform.Rotate(-YRotation, 0, 0);
}