1. Documentation
https://docs.unity3d.com/kr/current/ScriptReference/Input.GetAxis.html
Input-GetAxis - Unity 스크립팅 API
Returns the value of the virtual axis identified by axisName.
docs.unity3d.com
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// A very simplistic car driving on the x-z plane.
public class ${className} : MonoBehaviour
{
// 원하는 값 입력
public float speed = 10.0f;
public float rotationSpeed = 100.0f;
// Update is called once per frame
void Update()
{
// Get the horizontal and vertical axis.
// By default they are mapped to the arrow keys. (기본 키 값)
// The value is in the range -1 to 1 (반환 값)
float translation = Input.GetAxis("Vertical") * speed;
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
// Make it move 10 meters per second instead of 10 meters per frame... (프레임 기준이 아닌 초 기준)
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
// Move translation along the object's z-axis (z축을 기준으로 이동)
transform.Translate(0, 0, translation);
// Rotate around our y-axis (y축을 기준으로 회전)
transform.Rotate(0, rotation, 0);
}
}
2. 내 코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ${className} : MonoBehaviour
{
// 원하는 값 입력
public float speed = 10.0f;
// Update is called once per frame
void Update()
{
// ↑ : 1, ↓ : -1
float vTranslation = Input.GetAxis("Vertical") * speed;
// → : 1, ← : -1
float hTranslation = Input.GetAxis("Horizontal") * speed;
// 프레임 기준이 아닌 초 기준으로 이동
vTranslation *= Time.deltaTime;
hTranslation *= Time.deltaTime;
// Vector3.forward : (0,0,1)
transform.Translate(Vector3.forward * vTranslation);
// Vector3.right : (1,0,0)
transform.Translate(Vector3.right * hTranslation);
}
}
※ Time.deltaTime
- 기기마다 FPS가 다르기 때문에 동일한 속도로 객체를 이동시키기 위해 이를 조정해주는 값이다.
※ Translate
- 해당 벡터만큼 움직인다.
3. 마우스
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ${className} : MonoBehaviour
{
float horizontalSpeed = 2.0f;
float verticalSpeed = 2.0f;
// Update is called once per frame
void Update()
{
// Get the mouse delta. This is not in the range -1...1
float h = horizontalSpeed * Input.GetAxis("Mouse X");
float v = verticalSpeed * Input.GetAxis("Mouse Y");
// ↔ : x축, ↕ : z축 기준 회전
transform.Rotate(v, 0, h);
}
// 내장 함수
private void OnMouseEnter()
{
print("마우스가 들어왔습니다.");
}
private void OnMouseExit()
{
print("마우스가 나갔습니다.");
}
private void OnMouseDown()
{
print("마우스 버튼을 클릭했습니다.");
}
private void OnMouseUp()
{
print("마우스 버튼이 떨어졌습니다.");
}
}
'Unity' 카테고리의 다른 글
[Animator] 애니메이션 (0) | 2021.07.14 |
---|---|
[CharacterController] 캐릭터 이동 (0) | 2021.07.13 |
물체 충돌 (0) | 2021.07.13 |
[GetButton] Jump (0) | 2021.07.12 |
[GetKey] Input Keys (0) | 2021.07.12 |