PlayerMove 코드 : 캐릭터컨트롤러를 사용한 이동, 점프, 마우스 오른쪽클릭 줌인 기능
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEditor.Experimental.GraphView;
using UnityEditor.Rendering;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private CharacterController controller;
private Animator animator;
// 이동 코드
float input_x;
float input_z;
public float moveSpeed = 5f; // 캐릭터 이동 속도
bool runCheck; // 달리기 체크
// 점프 코드
public float jumpPower = 10f;
float gravity = -9.81f;
Vector3 velocity;
// 지면 체크
bool isGrounded;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
// 회전 코드
public float rotationSpeed = 15f; // 캐릭터 상하좌우 회전 속도
// 카메라 줌인 코드
public CinemachineVirtualCamera virtualCamera; // 줌인 할 카메라
void Start()
{
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
void Update()
{
PlayerMovement();
//PlayerTurn();
MouseClick();
}
/*
private void PlayerTurn()
{
//transform.Rotate();
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f); // 카메라의 상하 회전을 제한
cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); // 카메라 회전
playerBody.Rotate(Vector3.up * mouseX); // 플레이어 몸체 회전
}
*/
private void MouseClick()
{
if (Input.GetMouseButton(1))
{
virtualCamera.Priority = 16;
Debug.Log("Left mouse button is being held down");
}
else
{
virtualCamera.Priority = 14;
}
}
private void PlayerMovement()
{
// 지면 체크( 땅 밟고있는지 체크 )
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (velocity.y < 0 && isGrounded)
{
// 지면에 있을 때는 y 속도를 작은 음수로 설정 (지면에 붙여주는 역할)
velocity.y = -2f;
animator.SetBool("JumpOn", false);
}
input_x = Input.GetAxisRaw("Horizontal");
input_z = Input.GetAxisRaw("Vertical");
// 입력에 따른 상하 좌우 이동 설정
Vector3 move = new Vector3(input_x, 0, input_z).normalized;
// 캐릭터 회전
if (move != Vector3.zero) // 움직임이 있을때에만 회전하도록 조건문 설정
{
// 입력 방향으로 캐릭터 회전
Quaternion toRotation = Quaternion.LookRotation(move, Vector3.up);
print(toRotation);
// 부드러운 움직임
transform.rotation = Quaternion.Slerp(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
// 즉각적인 움직임
//transform.rotation = toRotation;
}
// 달리기 체크
runCheck = Input.GetKey(KeyCode.LeftShift);
// 왼쪽 쉬프트 누르면 달리기, 안누르면 걷기모션 재생하기 위한 코드
move = move * (runCheck ? 1 : 0.5f);
// 이동 구현
controller.Move(move * moveSpeed * Time.deltaTime);
// 애니메이터 Move에 값 전달
animator.SetFloat("Move", move.magnitude);
//print(move); // move값 확인
// 점프 입력 처리
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = jumpPower;
animator.SetTrigger("Jump");
animator.SetBool("JumpOn", true);
}
// 중력 적용
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
@ 리지드바디를 이용한 캐릭터 상하좌우 이동, 캐릭터 좌우 회전, 마우스 위아래 회전
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rigidMove : MonoBehaviour
{
Rigidbody myrigidbody;
public float walkSpeed = 15f; // 걷기 속도
public Camera cam;
public float mouseSensitivity = 2f; // 마우스 민감도
float currentCameraRotationX = 0;
// Start is called before the first frame update
void Start()
{
myrigidbody = GetComponent<Rigidbody>();
// 커서 안보이게 하기
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
Move();
CameraRotation();
CharacterRotation();
}
public void CharacterRotation()
{
// 좌우 캐릭터 회전
float yRotation = Input.GetAxisRaw("Mouse X");
Vector3 characterRotationY = new Vector3 (0, yRotation, 0) * mouseSensitivity;
myrigidbody.MoveRotation(myrigidbody.rotation * Quaternion.Euler(characterRotationY)); // 벡터3값(characterRotationY)을 쿼터니언으로 바꿔서 현재 회전값 Y에 곱해줌
}
public void CameraRotation()
{
// 상하 카메라 회전
float xRotation = Input.GetAxisRaw("Mouse Y");
float cameraRotationX = xRotation * mouseSensitivity;
currentCameraRotationX -= cameraRotationX;
currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, -45, 45);
cam.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0, 0);
}
public void Move()
{
// 상하좌우 이동
float X = Input.GetAxisRaw("Horizontal");
float Z = Input.GetAxisRaw("Vertical");
Vector3 XMove = transform.right * X;
Vector3 ZMove = transform.forward * Z;
Vector3 velocity = (XMove + ZMove).normalized * walkSpeed;
myrigidbody.MovePosition(transform.position + velocity * Time.deltaTime);
}
}
@ 캐릭터 컨트롤러 버전2 (진행중)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class CharacterControllerMove : MonoBehaviour
{
public float walkSpeed = 5f;
public float runSpeed = 10f;
public float mouseSensitivity = 2f;
private CharacterController characterController;
public GameObject skateboard; // 스케이트보드
// 애니메이터
Animator animator;
// 점프 코드
public float jumpPower = 8f;
float gravity = -9.81f;
Vector3 velocity;
// 카메라 회전
float currentCameraRotationX = 0;
public Camera cam;
// 지면 체크
bool isGrounded;
public Transform groundCheck;
public float groundDistance = 0.5f;
public LayerMask groundMask;
void Start()
{
characterController = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
skateboard.SetActive(false);
// 커서 안보이게 하기
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
Move();
CharacterRotation();
CameraRotation();
Aim();
}
public void Aim()
{
// 목표물 조준 및 식별
Transform camTransform = Camera.main.transform;
RaycastHit hit;
if (Physics.Raycast(camTransform.position, camTransform.forward, out hit, Mathf.Infinity))
{
print("Hit : " + hit.point);
}
}
public void CharacterRotation()
{
// 좌우 캐릭터 회전
float yRotation = Input.GetAxisRaw("Mouse X") * mouseSensitivity;
// 기존의 회전에 새로운 회전을 더하여 적용
transform.Rotate(0, yRotation, 0);
}
public void CameraRotation()
{
// 상하 카메라 회전
float xRotation = Input.GetAxisRaw("Mouse Y");
float cameraRotationX = xRotation * mouseSensitivity;
currentCameraRotationX -= cameraRotationX;
currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, -45, 45);
cam.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0, 0);
}
public void Move()
{
// 지면 체크( 땅 밟고있는지 체크 )
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (velocity.y < 0 && isGrounded)
{
// 지면에 있을 때는 y 속도를 작은 음수로 설정 (지면에 붙여주는 역할)
velocity.y = -2f;
animator.SetBool("JumpOn", false);
}
float moveX = Input.GetAxisRaw("Horizontal");
float moveZ = Input.GetAxisRaw("Vertical");
Vector3 move = transform.right * moveX + transform.forward * moveZ; // 1,0,0 * X 0,0,1 * Z
float moveSpeed = walkSpeed;
animator.SetFloat("x", moveX);
animator.SetFloat("y", moveZ);
if (Input.GetKey(KeyCode.LeftShift))
{
// 스케이트 보드 타기
/* if (!isOnSkateboard)
{
// 스케이트보드 생성 및 캐릭터 위치 조정
//skateboardInstance = Instantiate(skateboardPrefab, transform.position - new Vector3(0, characterController.height / 2, 0), Quaternion.identity);
skateboard.SetActive(true);
isOnSkateboard = true;
// 캐릭터의 Y 값을 스케이트보드 높이만큼 올리기
transform.position = new Vector3(transform.position.x, transform.position.y + skateboard.transform.localScale.y, transform.position.z);
characterController.Move(Vector3.up * skateboard.transform.localScale.y);
}*/
moveSpeed = runSpeed;
}
else
{
/*
if (isOnSkateboard)
{
// 스케이트보드 비활성화 및 캐릭터 위치 조정
//Destroy(skateboardInstance);
skateboard.SetActive(false);
isOnSkateboard = false;
// 캐릭터의 Y 값을 스케이트보드 높이만큼 내리기
transform.position = new Vector3(transform.position.x, transform.position.y - skateboard.transform.localScale.y, transform.position.z);
characterController.Move(Vector3.down * skateboard.transform.localScale.y);
}*/
}
print("is Grounded : " + isGrounded);
move.Normalize();
// 상하좌우 이동
characterController.Move(move * moveSpeed * Time.deltaTime);
// 점프 입력 처리
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = jumpPower;
animator.SetTrigger("Jump");
animator.SetBool("JumpOn", true);
}
// 중력 적용
velocity.y += gravity * Time.deltaTime;
// 중력 및 점프 적용
characterController.Move(velocity * Time.deltaTime);
//print("G velocity.y : " + velocity.y);
}
}
문제1. 캐릭터 컨트롤러 사용시 transform.position 변경 불가. (0) | 2024.08.05 |
---|