Skip to content

Instantly share code, notes, and snippets.

@2RiniaR
Created February 15, 2019 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2RiniaR/c30efb0124de96c8e4c4973ff911e7a2 to your computer and use it in GitHub Desktop.
Save 2RiniaR/c30efb0124de96c8e4c4973ff911e7a2 to your computer and use it in GitHub Desktop.
UnityでMinecraftみたいなカメラの挙動を実装するスクリプト
/*
【 マウス+WASDキーによるカメラ操作 】
作成者:watano
必ずカメラにアタッチしてください。
Space : 上移動(+y)
Shift : 下移動(-y)
W : 前移動(+z)
S : 後移動(-z)
A : 左移動(-x)
D : 右移動(+x)
マウス移動 : カメラの向きを調整
@param
float MoveSpeed //カメラ移動速度
float RotationSpeed //カメラ回転速度
bool isCursorVisible //カーソルを表示するか
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
[RequireComponent(typeof(Camera))]
public class MoveCamera : MonoBehaviour {
public float MoveSpeed;
public float RotationSpeed;
public bool isCursorVisible;
Camera MyCamera;
Transform MyTransForm;
private Vector3 NewAngle = new Vector3(0, 0, 0);
// Use this for initialization
void Start () {
MyCamera = GetComponent<Camera>();
MyTransForm = MyCamera.GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
Rotate();
Move();
Cursor.visible = isCursorVisible;
}
void Rotate(){
NewAngle.y += Input.GetAxis("Mouse X") * RotationSpeed;
NewAngle.x -= Input.GetAxis("Mouse Y") * RotationSpeed;
NewAngle.z = 0;
if(NewAngle.x < -90) NewAngle.x = -90;
if(NewAngle.x > 90) NewAngle.x = 90;
MyCamera.transform.localEulerAngles = NewAngle;
}
void Move(){
Vector3 Move_Y = new Vector3(0, 0, 0);
Vector3 Move_XZ = new Vector3(0, 0, 0);
Move_Y.y += Input.GetAxisRaw("Vertical_Y") * MoveSpeed;
Move_XZ.x += Input.GetAxisRaw("Horizontal_X") * MoveSpeed;
Move_XZ.z += Input.GetAxisRaw("Horizontal_Z") * MoveSpeed;
MyTransForm.position += Move_Y;
Vector3 MoveXZcross = MyTransForm.rotation * Move_XZ;
MyTransForm.position += new Vector3(MoveXZcross.x, 0, MoveXZcross.z);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment