상세 컨텐츠

본문 제목

유니티 낙서장

카테고리 없음

by MJ_119 2024. 10. 25. 17:01

본문

 

- 리지드 바디 이동, 점프, Q누르면 날기 

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class MoveFixedUpdate : MonoBehaviour
{
    // 이동 구현
    private Rigidbody rb;
    public float moveSpeed = 7f; // 캐릭터 이동 속도
    private float horizontal;
    private float vertical;
    public float blendMove;
    Vector3 moveInput;

    // 회전
    public float rotationSpeed = 10f; // 회전 속도

    // 점프 구현
    public float jumpHeight = 7f;
    private bool isJump;
    private bool jump;

    // 활강 구현
    public float glideSpeed = 2;
    public float glideFallSpeed = 0.2f;
    private bool isGliding = false;

    Animator animator;

    void Start()
    {
        // 커서 안보이게 하기
        //Cursor.lockState = CursorLockMode.Locked;

        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        // 매 프레임 입력 받기
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        jump = Input.GetButtonDown("Jump");

        CharacterJump();
        JumpAttack();

        moveInput = new Vector3(horizontal, 0.0f, vertical);

        // 움직일 때만 움직이는 방향으로 회전
        if (moveInput != Vector3.zero)
        { 
            // 회전
            Quaternion targetRotation = Quaternion.LookRotation(moveInput);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }

        // 블렌드 트리 이동 애니메이션
        float blendMove = new Vector3(horizontal, 0, vertical).magnitude;
        animator.SetFloat("Speed", blendMove);


        // 활강 구현
        if (Input.GetKeyDown(KeyCode.Q)) // Q 누르면 글라이딩 시작
        {
            GlidingStart();
        }
        if (Input.GetKeyUp(KeyCode.Q)) // Q 떼면 글라이딩 종료
        {
            GlidingStop();
        }
    }

    private void FixedUpdate()
    {
        CharacterMove();

        if (isGliding)
        {
            Gliding();
        }
    }
    public void GlidingStart()
    {
        isGliding = true;
        rb.useGravity = false;
        animator.SetBool("Gliding", true);
    }
    public void GlidingStop()
    {
        isGliding = false;
        rb.useGravity = true;
        animator.SetBool("Gliding", false);
    }

    public void Gliding()
    {

        // 키 입력 받은 방향으로 서서히 낙하
        //rb.velocity = new Vector3(moveInput.x, glideSpeed, moveInput.z);

        Vector3 forwardMovement = transform.forward * glideSpeed;
        Vector3 glideMovement = new Vector3(forwardMovement.x, -glideFallSpeed, forwardMovement.z);
        rb.velocity = glideMovement;
    }

    public void CharacterJump()
    {
        if (jump && !isJump) // 키 입력받고 isJump가 false면 아래 코드 진행
        {
            animator.SetTrigger("Jump"); // 점프 스타트 jump start

            animator.SetBool("Jumping", true); // 점프 중 jump air

            rb.AddForce(transform.up * jumpHeight, ForceMode.Impulse);
            isJump = true; // 점프중


        }
    }

    // 바닥과의 충돌 감지
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            animator.SetBool("Jumping", false); // 점프 착지 jump landing
            isJump = false; // 점프 끝

            // 활강 끝
            animator.SetBool("Gliding", false);
            isGliding = false;

        }

        if (collision.gameObject.CompareTag("InvertGravityZone"))
        {
            animator.SetBool("GravityZone", true);
        }
    }

    public void CharacterMove()
    {

        // 입력 벡터 정규화 및 크기 조정
        if (moveInput.magnitude > 1)
        {
            moveInput = moveInput.normalized;
        }

        // 새로운 위치 계산
        Vector3 newPosition = rb.position + moveInput * moveSpeed * Time.fixedDeltaTime;

        // Rigidbody 속도를 0으로 설정하여 미끄러짐 방지
        //rb.velocity = Vector3.zero;

        // MovePosition으로 새로운 위치로 이동
        rb.MovePosition(newPosition);
    }



    // 점프 공격
    public void JumpAttack()
    {
        if (Input.GetMouseButtonDown(1)) // 마우스 우클릭
        {
            // 공중에서 떨어지지않고 멈춰서 애니메이션 동작하도록 Kinematic 활성화
            rb.isKinematic = true;
            animator.SetTrigger("JumpAttack"); // 점프 도중 공격

            // 2초뒤 다시 떨어지도록 Kinematic 비활성화
            Invoke("AttackTime", 1.1f);
        }
    }

    public void AttackTime()
    {
        // Kinematic 비활성화
        rb.isKinematic = false;
    }


    // 중력 반전 구역
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("InvertGravityZone"))
        {
            InvertGravity(true);
            animator.SetTrigger("GravityOn");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("InvertGravityZone"))
        {
            InvertGravity(false);
        }
    }
    private void InvertGravity(bool invert)
    {
        Physics.gravity = invert ? new Vector3(0, 9.81f, 0) : new Vector3(0, -9.81f, 0);

        // 캐릭터의 축 변경

        // 캐릭터의 스케일을 반전
        //Vector3 scale = transform.localScale;
        //scale.y *= -1;
        //transform.localScale = scale;

        // Rigidbody의 속도를 반전
        //Vector3 velocity = rb.velocity;
        //velocity.y *= -1;
        //rb.velocity = velocity;
    }
}

 

 

 

- 큐브에 닿으면 캐릭터를 다른 큐브 위치로 이동시킴. ( 순간이동 )

using UnityEngine;

public class Respawn : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform RespawnPosition;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            player.transform.position = RespawnPosition.transform.position;
            Physics.SyncTransforms();
        }
    }
}