2D 포물선으로 날아갈 때 바라보는 방향 설정

유니티 C# 2020. 11. 25. 18:36

출처: luminaryapps.com/blog/arcing-projectiles-in-unity/

 

Luminary Apps : Blog

A frequently asked question in both the Unity forums and on Unity Answers is: How do I make a projectile arc to its target, like an arrow shot from a bow?  I've seen (and given) lots of different answers to this question, and honestly, most of them are un

luminaryapps.com

 

using UnityEngine;

using UnityEngine.Events;

using System.Collections.Generic;

 

public class Projectile : MonoBehaviour

{

     [Tooltip("Position we want to hit")] public Vector3 targetPos;

     [Tooltip("Horizontal speed, in units/sec")] public float speed = 10;

     [Tooltip("How high the arc should be, in units")] public float arcHeight = 1;

 

     Vector3 startPos; void Start()

     {

          // Cache our start position, which is really the only thing we need

          // (in addition to our current position, and the target).

          startPos = transform.position;

}

 

void Update()

{

          // Compute the next position, with arc added in

          float x0 = startPos.x;

          float x1 = targetPos.x;

          float dist = x1 - x0;

          float nextX = Mathf.MoveTowards(transform.position.x, x1, speed * Time.deltaTime);

          float baseY = Mathf.Lerp(startPos.y, targetPos.y, (nextX - x0) / dist);

          float arc = arcHeight * (nextX - x0) * (nextX - x1) / (-0.25f * dist * dist);

          nextPos = new Vector3(nextX, baseY + arc, transform.position.z);

 

          // Rotate to face the next position, and then move there

          transform.rotation = LookAt2D(nextPos - transform.position);

          transform.position = nextPos;

 

          // Do something when we reach the target

          if (nextPos == targetPos) Arrived();

}

 

void Arrived()

{

          Destroy(gameObject);

}

///

/// This is a 2D version of Quaternion.LookAt; it returns a quaternion

/// that makes the local +X axis point in the given forward direction.

///

/// forward direction

/// Quaternion that rotates +X to align with forward

static Quaternion LookAt2D(Vector2 forward)

{

     return Quaternion.Euler(0, 0, Mathf.Atan2(forward.y, forward.x) * Mathf.Rad2Deg);

}

}