지금 캐릭터를 클릭한 곳에 이동시키고자 하고 있습니다 ㅠㅜ 그런데 여기서 막히고 있네요 ㅠㅜ
한번 스크립트를 봐주시고 어떤게 문제인지 알려주실 수 있으실려나요 ㅠ??
일단, 구현하고자 하는 것은 웨이 포인트로 지정한 point(빈 오브젝트)들이 있는데, 그 오브젝트를 클릭하면 현재 위치 point에서 클릭한 point로 이동하는걸 구현하고자 합니다..
지금 밑에 코드는 그걸 구현해보고자 여러 곳에서 코드를 보고 합쳐본 거긴 한데...
업데이트 부분에서 오브젝트를 클릭시 라는 조건은 어떻게 적어줘야 할까요???
그리고 현재는 무조건 스타트 지점이 정해져 있는데 (게임 플레이를 누르면 무조건 point 오브젝트(첫번째 point 오브젝트)위에서 시작해서 마지막 오브젝트인 point4 오브젝트까지 이동 후 멈춤으로 되어있는데, 서있는 장소에서 클릭한 장소로 이동하는 것으로 바꾸고 싶으면 어느 부분을 건들여 줘야 할까요 ㅠ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine;
namespace WaypointsFree
{
{
///
/// Moves the gameobject through a series of waypoints
///
///
public class WaypointsTraveler : MonoBehaviour
{
[Tooltip("WaypointsGroup gameobject containing the waypoints to travel.")]
public WaypointsGroup Waypoints = null;
/// Moves the gameobject through a series of waypoints
///
///
public class WaypointsTraveler : MonoBehaviour
{
[Tooltip("WaypointsGroup gameobject containing the waypoints to travel.")]
public WaypointsGroup Waypoints = null;
[Tooltip("Movement and look-at constraints.")]
public PositionConstraint XYZConstraint = PositionConstraint.XYZ;
public PositionConstraint XYZConstraint = PositionConstraint.XYZ;
[Tooltip("Auto-start movement if true.")]
public bool AutoStart = false;
//[Range(0,float.MaxValue)]
public float MoveSpeed = 5.0f;
public float MoveSpeed = 5.0f;
//[Range(0, float.MaxValue)]
public float LookAtSpeed = 3.0f;
public float LookAtSpeed = 3.0f;
[Tooltip("Starts movement from the position vector at this index. Dependent upon StartTravelDirection!")]
public int StartIndex = 0;
public int StartIndex = 0;
[Tooltip("Immediately move starting position to postion at StartIndex.")]
public bool AutoPositionAtStart = true;
[Tooltip("Initial direction of travel through the positions list.")]
public TravelDirection StartTravelDirection = TravelDirection.FORWARD;
public TravelDirection StartTravelDirection = TravelDirection.FORWARD;
[Tooltip("Movement behavior to apply when last postion reached.")]
public EndpointBehavior EndReachedBehavior = EndpointBehavior.LOOP;
public EndpointBehavior EndReachedBehavior = EndpointBehavior.LOOP;
[Tooltip("Movement function type")]
public MoveType StartingMovementType = MoveType.LERP;
public MoveType StartingMovementType = MoveType.LERP;
public bool IsMoving
{
get { return isMoving; }
}
delegate bool MovementFunction ();
MovementFunction moveFunc = null;
MovementFunction moveFunc = null;
int positionIndex = -1; // Index of the next waypoint to move toward
List waypointsList; //Reference to the list of waypoints located in Waypoints
Vector3 nextPosition; // The next position to travel to.
Vector3 startPosition;
Vector3 destinationPosition;
float distanceToNextWaypoint;
float distanceTraveled = 0;
float timeTraveled = 0;
float distanceTraveled = 0;
float timeTraveled = 0;
int travelIndexCounter = 1;
bool isMoving = false; // Movement on/off
Vector3 positionOriginal;
Quaternion rotationOriginal;
float moveSpeedOriginal = 0;
float lookAtSpeedOriginal = 0;
Quaternion rotationOriginal;
float moveSpeedOriginal = 0;
float lookAtSpeedOriginal = 0;
private bool Temp = false;
Camera _mainCam = null;
///
/// 마우스의 상태
///
private bool _mouseState;
/// 마우스의 상태
///
private bool _mouseState;
///
/// 마우스가 다운된 오브젝트
///
private GameObject target;
///
/// 마우스 좌표
///
private Vector3 MousePos;
/// 마우스가 다운된 오브젝트
///
private GameObject target;
///
/// 마우스 좌표
///
private Vector3 MousePos;
public void ResetTraveler()
{
transform.position = positionOriginal;
transform.rotation = rotationOriginal;
MoveSpeed = moveSpeedOriginal;
LookAtSpeed = lookAtSpeedOriginal;
LookAtSpeed = lookAtSpeedOriginal;
StartAtIndex(StartIndex, AutoPositionAtStart);
SetNextPosition();
travelIndexCounter = StartTravelDirection == TravelDirection.REVERSE ? -1 : 1;
if (StartingMovementType == MoveType.LERP)
moveFunc = MoveLerpSimple;
else if (StartingMovementType == MoveType.FORWARD_TRANSLATE)
moveFunc = MoveForwardToNext;
moveFunc = MoveLerpSimple;
else if (StartingMovementType == MoveType.FORWARD_TRANSLATE)
moveFunc = MoveForwardToNext;
}
// Start is called before the first frame update
void Start()
{
moveSpeedOriginal = MoveSpeed;
lookAtSpeedOriginal = LookAtSpeed;
void Start()
{
moveSpeedOriginal = MoveSpeed;
lookAtSpeedOriginal = LookAtSpeed;
positionOriginal = transform.position;
rotationOriginal = transform.rotation;
rotationOriginal = transform.rotation;
ResetTraveler();
Move( AutoStart );
_mainCam = Camera.main;
}
public void Move(bool tf)
{
isMoving = tf;
}
{
isMoving = tf;
}
private void Awake()
{
if (Waypoints != null)
{
waypointsList = Waypoints.waypoints;
}
}
{
if (Waypoints != null)
{
waypointsList = Waypoints.waypoints;
}
}
// Update is called once per frame
void Update()
{
////마우스가 내려갔는지?
//if (true == Input.GetMouseButtonDown(0))
//{
// //내려갔다.
void Update()
{
////마우스가 내려갔는지?
//if (true == Input.GetMouseButtonDown(0))
//{
// //내려갔다.
// //타겟을 받아온다.
// target = GetClickedObject();
// target = GetClickedObject();
// //타겟이 나인가?
// if (true == target.Equals(gameObject))
// {
// //있으면 마우스 정보를 바꾼다.
// _mouseState = true;
// }
// if (true == target.Equals(gameObject))
// {
// //있으면 마우스 정보를 바꾼다.
// _mouseState = true;
// }
//}
//else if (true == Input.GetMouseButtonUp(0))
//{
// //마우스가 올라 갔다.
// //마우스 정보를 바꾼다.
// _mouseState = false;
//}
//else if (true == Input.GetMouseButtonUp(0))
//{
// //마우스가 올라 갔다.
// //마우스 정보를 바꾼다.
// _mouseState = false;
//}
////마우스가 눌렸나?
////스케일을 조절하여 클릭됬음을 확인한다.
//if (true == _mouseState)
//{
// //눌렸다!
// Temp = true;
//}
////스케일을 조절하여 클릭됬음을 확인한다.
//if (true == _mouseState)
//{
// //눌렸다!
// Temp = true;
//}
if (Temp == true)
{
if (isMoving == true && moveFunc != null)
{
bool arrivedAtDestination = false;
{
if (isMoving == true && moveFunc != null)
{
bool arrivedAtDestination = false;
// Call the delegate Movement Function...
arrivedAtDestination = moveFunc();
arrivedAtDestination = moveFunc();
if (arrivedAtDestination == true)
{
SetNextPosition();
}
{
SetNextPosition();
}
//Temp = false;
}
}
}
}
}
}
///
/// 마우스가 내려간 오브젝트를 가지고 옵니다.
///
/// 선택된 오브젝트
//private GameObject GetClickedObject()
//{
// //충돌이 감지된 영역
// RaycastHit hit;
// //찾은 오브젝트
// GameObject target = null;
// //마우스 포이트 근처 좌표를 만든다.
// Ray ray = _mainCam.ScreenPointToRay(Input.mousePosition);
// Ray ray = _mainCam.ScreenPointToRay(Input.mousePosition);
// //마우스 근처에 오브젝트가 있는지 확인
// if (true == (Physics.Raycast(ray.origin, ray.direction * 10, out hit)))
// {
// //있다!
// if (true == (Physics.Raycast(ray.origin, ray.direction * 10, out hit)))
// {
// //있다!
// //있으면 오브젝트를 저장한다.
// target = hit.collider.gameObject;
// }
// target = hit.collider.gameObject;
// }
// return target;
//}
//}
///
/// Setup the list of positions to follow
///
/// List of Vector3s indicating move-to locations
public void SetWaypointsGroup(WaypointsGroup newGroup)
{
Waypoints = newGroup;
waypointsList = null;
if(newGroup != null)
{
waypointsList = newGroup.waypoints;
}
}
///
/// Sets the position to beging moving toward; if autpAupdatePostion is true, then start
/// at that index-related position immediately.
///
///
///
void StartAtIndex(int ndx, bool autoUpdatePosition = true)
{
if (StartTravelDirection == TravelDirection.REVERSE)
ndx = waypointsList.Count - ndx - 1;
ndx = Mathf.Clamp(ndx, 0, waypointsList.Count - 1);
positionIndex = ndx - 1;
if (autoUpdatePosition)
{
transform.position = waypointsList[ndx].GetPosition();
if(LookAtSpeed > 0)
{
if (StartTravelDirection == TravelDirection.REVERSE)
{
ndx -= 1;
if (ndx }
else
{
ndx += 1;
if (ndx >= waypointsList.Count)
ndx = 0;
}
positionIndex = ndx - 1;
if (autoUpdatePosition)
{
transform.position = waypointsList[ndx].GetPosition();
if(LookAtSpeed > 0)
{
if (StartTravelDirection == TravelDirection.REVERSE)
{
ndx -= 1;
if (ndx }
else
{
ndx += 1;
if (ndx >= waypointsList.Count)
ndx = 0;
}
/*
Waypoint wp = waypointsList[ndx];
Vector3 wpPos = wp.GetPosition();
Vector3 worldUp = Vector3.forward;
Waypoint wp = waypointsList[ndx];
Vector3 wpPos = wp.GetPosition();
Vector3 worldUp = Vector3.forward;
transform.LookAt(wpPos, worldUp);
*/
}
}
}
*/
}
}
}
///
/// Fetch the next waypoint position in the waypoints list
/// Depending on Endpoint behavior, ping pong, loop, or stop.
/// - Stop : Stops movement at the endpoint
/// - Ping Pong: reverses traveseral of the Waypoint Positions list
/// - Loop : Resets the index to 0; restarting at the first waypoint
///
void SetNextPosition()
{
int posCount = waypointsList.Count;
if (posCount > 0)
{
/// Fetch the next waypoint position in the waypoints list
/// Depending on Endpoint behavior, ping pong, loop, or stop.
/// - Stop : Stops movement at the endpoint
/// - Ping Pong: reverses traveseral of the Waypoint Positions list
/// - Loop : Resets the index to 0; restarting at the first waypoint
///
void SetNextPosition()
{
int posCount = waypointsList.Count;
if (posCount > 0)
{
// Reached the endpoint; determing what do do next
if( (positionIndex == 0 && travelIndexCounter 0))
{
// Stop moving when an endpoint is reached
if(EndReachedBehavior == EndpointBehavior.STOP)
{
isMoving = true;
return;
}
if( (positionIndex == 0 && travelIndexCounter 0))
{
// Stop moving when an endpoint is reached
if(EndReachedBehavior == EndpointBehavior.STOP)
{
isMoving = true;
return;
}
// Continue movement, but reverse direction
else if(EndReachedBehavior == EndpointBehavior.PINGPONG)
{
travelIndexCounter = -travelIndexCounter;
}
else if(EndReachedBehavior == EndpointBehavior.PINGPONG)
{
travelIndexCounter = -travelIndexCounter;
}
// General Loop (default)
else if (EndReachedBehavior == EndpointBehavior.LOOP)
{
}
else if (EndReachedBehavior == EndpointBehavior.LOOP)
{
}
}
positionIndex += travelIndexCounter;
if (positionIndex >= posCount)
positionIndex = 0;
else if (positionIndex positionIndex = posCount - 1;
positionIndex = 0;
else if (positionIndex positionIndex = posCount - 1;
nextPosition = waypointsList[positionIndex].GetPosition();
if (XYZConstraint == PositionConstraint.XY)
{
nextPosition.z = transform.position.z;
}
else if (XYZConstraint == PositionConstraint.XZ)
{
nextPosition.y = transform.position.y;
}
ResetMovementValues();
}
}
}
}
///
/// Reset movement metrics based on the current transform postion and the next waypoint.
///
void ResetMovementValues()
{
// Update current position, distance, and start time -- used in Update to move the transform
startPosition = transform.position;
destinationPosition = nextPosition;
distanceToNextWaypoint = Vector3.Distance(startPosition, destinationPosition);
distanceTraveled = 0;
timeTraveled = 0;
/// Reset movement metrics based on the current transform postion and the next waypoint.
///
void ResetMovementValues()
{
// Update current position, distance, and start time -- used in Update to move the transform
startPosition = transform.position;
destinationPosition = nextPosition;
distanceToNextWaypoint = Vector3.Distance(startPosition, destinationPosition);
distanceTraveled = 0;
timeTraveled = 0;
}
///
/// Uses a Vector3 Lerp function to update the gameobject's transform position.
/// MoveSpeed needs to be > 0
///
///
bool MoveLerpSimple()
{
if (MoveSpeed MoveSpeed = 0;
/// Uses a Vector3 Lerp function to update the gameobject's transform position.
/// MoveSpeed needs to be > 0
///
///
bool MoveLerpSimple()
{
if (MoveSpeed MoveSpeed = 0;
timeTraveled += Time.deltaTime;
distanceTraveled += Time.deltaTime * MoveSpeed;
float fracAmount = distanceTraveled / distanceToNextWaypoint;
transform.position = Vector3.Lerp(startPosition, destinationPosition, fracAmount);
// set LookAt speed to 0 if no rotation toward the destination is desired.
UpdateLookAtRotation();
return fracAmount >= 1;
}
distanceTraveled += Time.deltaTime * MoveSpeed;
float fracAmount = distanceTraveled / distanceToNextWaypoint;
transform.position = Vector3.Lerp(startPosition, destinationPosition, fracAmount);
// set LookAt speed to 0 if no rotation toward the destination is desired.
UpdateLookAtRotation();
return fracAmount >= 1;
}
///
/// Translates the waypoint traveler using the forward direction. Note that "forward" is dependent
/// upon the directional/position constraint.
/// - XYZ: Vector3.forward
/// - XY : Vector3.up
/// - XZ : Vector3.right
///
/// -- When using this method of translation, LOOKATSPEED must be > 0.
///
///
bool MoveForwardToNext()
{
if (MoveSpeed MoveSpeed = 0;
/// Translates the waypoint traveler using the forward direction. Note that "forward" is dependent
/// upon the directional/position constraint.
/// - XYZ: Vector3.forward
/// - XY : Vector3.up
/// - XZ : Vector3.right
///
/// -- When using this method of translation, LOOKATSPEED must be > 0.
///
///
bool MoveForwardToNext()
{
if (MoveSpeed MoveSpeed = 0;
float rate = Time.deltaTime * MoveSpeed;
float distance = Vector3.Distance(transform.position, destinationPosition);
if (distance {
transform.position = destinationPosition;
return true;
}
float distance = Vector3.Distance(transform.position, destinationPosition);
if (distance {
transform.position = destinationPosition;
return true;
}
// If lookatspeed is 0, then set it to max; this method of movement requires
// the gameobject transform to be looking toward it's destination
if (LookAtSpeed <= 0) LookAtSpeed = float.MaxValue;
// the gameobject transform to be looking toward it's destination
if (LookAtSpeed <= 0) LookAtSpeed = float.MaxValue;
UpdateLookAtRotation();
Vector3 moveDir = Vector3.forward;
if (XYZConstraint == PositionConstraint.XY)
{
moveDir = Vector3.up;
}
if (XYZConstraint == PositionConstraint.XY)
{
moveDir = Vector3.up;
}
transform.Translate(moveDir * rate);
return false;
}
///
/// Rotate the traveler to "look" at the next waypoint.
/// Note: When using the FORWARD_TRANSLATE movement mode, LookAtSpeed is always > 0
///
void UpdateLookAtRotation()
{
// LookatSpeed is 0; no rotating...
if (LookAtSpeed <= 0) return;
/// Rotate the traveler to "look" at the next waypoint.
/// Note: When using the FORWARD_TRANSLATE movement mode, LookAtSpeed is always > 0
///
void UpdateLookAtRotation()
{
// LookatSpeed is 0; no rotating...
if (LookAtSpeed <= 0) return;
float step = LookAtSpeed * Time.deltaTime;
Vector3 targetDir = nextPosition - transform.position;
Vector3 targetDir = nextPosition - transform.position;
if (XYZConstraint == PositionConstraint.XY)
{
float angle = Mathf.Atan2(targetDir.y, targetDir.x) * Mathf.Rad2Deg - 90;
Quaternion qt = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qt, step);
}
else if (XYZConstraint == PositionConstraint.XZ)
{
float angle = Mathf.Atan2(targetDir.x, targetDir.z) * Mathf.Rad2Deg;
Quaternion qt = Quaternion.AngleAxis(angle, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qt, step);
}
else
{
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0f);
// Move our position a step closer to the target.
transform.rotation = Quaternion.LookRotation(newDir);
{
float angle = Mathf.Atan2(targetDir.x, targetDir.z) * Mathf.Rad2Deg;
Quaternion qt = Quaternion.AngleAxis(angle, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qt, step);
}
else
{
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0f);
// Move our position a step closer to the target.
transform.rotation = Quaternion.LookRotation(newDir);
}
}
}
}
}
대충보니 오브젝트 클릭시 타겟얻어오는거 주석처리되있네 그거 풀면 target변수에 오브젝트 얻어지는거 같은데 그거로 위치정하면될듯
저거 주석안되어있던거였는데 아무리 오브젝트를 클릭해도 말그대로 클릭만 될뿐 이동은 안되서 일단 주석처리 해둿던 ㅠ
일단 이 스크립트 자체가 캐릭터에게 들어가 있긴 합니다 ㅠ
미치고 팔짝 뛰겠는게,,, 최종 목표는 웨이포인트로 지정해둔 오브젝트를 클릭 시 그곳으로 이동하게 하는게 목표인데,,, 클릭하는 것 부터가 막혀있는 ㅠ
밑댓글처럼 그냥 유니티 네비게이션 쓰고 지면 클릭했을때 위치구해서 네비게이션으로 이동하면 길찾기알고리즘으로 진행함. 이건 네비게이션 이동 예제같은거 찾아보고
이건 사실 애매하다. 혹시 3디면 걍 네비게이션 메쉬써
ㅇㅇ?? 네비게이션 메쉬?? 그것도 알려준 tween 들이랑 비슷한 건가요? 위의 스크립트가 tween 찾다가 얻게 된 코드인데
지금 목표가 화면을 클릭하면 정해진 길대로 움직여서 클릭한 곳으로 도착하는게 최종 목표인데,,, 저 코드대로라면 (클릭 이벤트 같은거 빼고 걍 키보드 입력으로 했을 때는) 정해진 길을 한바퀴 쭉 돌고 마지막 포인트에서 멈추고 끝인지라 ㅠ