@ 비행기가 정면을 바라보게끔 하고 상하좌우 이동할 때 기체를 회전하며 움직이기
using UnityEngine;
public class PlayerFly : MonoBehaviour
{
float xInput, yInput;
[SerializeField] float xLimit = 5f;
[SerializeField] float yLimit = 5f;
[SerializeField] float playerSpeed = 25f;
[SerializeField] float pitchFacter = -2f;
[SerializeField] float controllFactor = -15f;
[SerializeField] float yawPitchFacter = 5f;
[SerializeField] float controllRollFactor = -15f;
void Start()
{
}
// Update is called once per frame
void Update()
{
MovePlayer();
RotatePlayer();
}
void RotatePlayer()
{
float pitch = transform.localPosition.y * pitchFacter + yInput * controllFactor;
float yaw = transform.localPosition.x * yawPitchFacter;
float roll = xInput * controllRollFactor;
transform.localRotation = Quaternion.Euler(pitch + 90f, yaw, roll);
}
private void MovePlayer()
{
xInput = Input.GetAxis("Horizontal");
yInput = Input.GetAxis("Vertical");
float X = xInput * Time.deltaTime * playerSpeed;
float Y = yInput * Time.deltaTime * playerSpeed;
float moveX = transform.localPosition.x + X;
float moveY = transform.localPosition.y + Y;
float clampX = Mathf.Clamp(moveX, -xLimit, xLimit);
float clampY = Mathf.Clamp(moveY, -2.5f, yLimit);
transform.localPosition = new Vector3(clampX, clampY, transform.localPosition.z);
}
}
이 코드는 비행기나 우주선과 같은 3D 객체를 제어할 때 자주 사용되는 방식입니다. 예를 들어, 비행기의 경우:
이 함수는 이러한 3D 객체의 방향을 사용자의 입력에 따라 유연하게 조정해 줍니다.
- pitch값에 + 90f 을 한 이유 : 캐릭터가 기본방향이 위를 향해있기 때문
- 90을 더해주면 비행하는 것처럼 날아다니게 보임
유니티 팁 여러개 오브젝트 정렬하기 (0) | 2024.08.29 |
---|---|
유니티 기본 C# 스크립트 내용 수정하기(start,update) (0) | 2024.08.29 |
유니티 Mathf.Clamp() 특정값을 범위로 제한하기 (0) | 2024.08.29 |
유니티 오브젝트 상하좌우로 왔다갔다 하기 (0) | 2024.08.27 |
유니티 다음 씬으로 넘어가기, 현재 씬 인덱스 구하기 (0) | 2024.08.26 |