응용프로그램/유니티(Unity)

Unity - 이동 및 회전

zelkova 2016. 10. 2. 16:53

 

<목차로 돌아가기>

 

 

 

알면 좋은 소스

Input.GetAxis ("받아들일 행동")
GetAxis의 이동을 부드럽게~ 받아들임

 

Input.GetAxisRaw ("받아들일 행동")

GetAxis의 이동을 즉시 받아들임

 

transform.LookAt(point);

point의 방향으로 바라본다.

 

imgLoading.rectTransform.Rotate(new Vector3(0, 0, -2));

z방향으로 -2만큼 회전시킴.

 

 

회전참조

 

캐릭터 움직이는 예지

 

Player.cs

 

  1. using UnityEngine; 
  2.  using System.Collections;
  3.  [RequireComponent (typeof (PlayerController))]
  4.  public class Player : MonoBehaviour
  5.  {
  6.     public float moveSpeed = 5;
  7.     PlayerController controller;
  8.     void Start()
  9.     {
  10.        controller =GetComponent<PlayerController>();
  11.     }
  12.     void Update()
  13.     {
  14.        Vector3 moveInput = new Vector3(Input.GetAxis("Horizontal"), 0, 
  15.        Input.GetAxis("Vertical"));
  16.  
  17.        Vector3 MoveVelocity = moveInput.normalized * moveSpeed;
  18.        controller.Move(MoveVelocity);
  19.     }
  20.  }
 
3줄 : [RequireComponent (typeof (PlayerController))]
   controller = GetComponent<playerController> ();
이부분이 에러를 나지않게 PlayerController와 붙어서 움직이는 것을 강제함.
 
7줄 :  PlayerController controller;
  컨트롤러를 할당
 
10줄 : controller = GetComponent<PlayerController> ();
   GetComponent로 PlayerController를 가져옵니다.
 
14줄 : Vector3 moveInput = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
   움직임 임력받기 수평, 높이, 수직
 
17줄 : Vector3 MoveVelocity = moveInput.normalized * moveSpeed;
   입력의 방향을 얻기 위해 MoveInput를 정규화(nomalized)하여 가져옵니다.
   ("nomarlized는 방향을 가리키는 단위벡터로 만드는 연산입니다.)
 
18줄 : controller.Move(MoveVelocity);
   컨트롤러 객체에서 Move 메소드를 가져와서 moveVelocity변수를 넘겨줍니다.
 
 
 

 

PlayerController.cs

  1. using UnityEngine; 
  2.  using System.Collections; 
  3.  [RequireComponent (typeof (Rigidbody))]
  4.  public class PlayerController : MonoBehaviour
  5.  {
  6.     Vector3 velocity;
  7.     Rigidbody myRigidbody;
  8.     void Start()
  9.     {
  10.        myRigidbody = GetComponent();
  11.     }
  12.     public void Move(Vector3 _velocity)
  13.     {
  14.        velocity = _velocity;
  15.     }
  16.     public void FixedUpdate()
  17.     {
  18.        myRigidbody.MovePosition(myRigidbody.position + 
  19.       velocity * Time.fixedDeltaTime);
  20.     }
  21.  }

 

16줄 : public void FixedUpdate()
   짧고 반복적으로 실행되게 할때는 FixedUpdate()를 사용한다. 
   FixedUpdate()를 사용하면 프레임 저하가 발생해도 프레임에 시간의 가중치를 곱해
   실행되어 이동속도를 유지함 
 
TIP 스무스하게 움직이는 오브젝트가 마음에 들지 않다면!
GetAxis를 GetAxisRaw를 사용하면 방향키에서 손을 때는순간 멈춤
 
TIP 기울기 굳히기
오브젝트 클릭 → Inspecter → Constraints → Freeze Rotation → 모두체크
 
캐릭터 이동과 회전 예제2
  1. using UnityEngine;
  2.  using System.Collections;
  3.  
  4.  public class NewBehaviourScript : MonoBehaviour {
  5.  
  6.     
  7.     Rigidbody moveRigibody;
  8.     
  9.  
  10.     float moveHorizontal;
  11.     float moveVertical;
  12.     Vector3 moveInput;
  13.     public int speed;
  14.  
  15.     Transform transform;
  16.     
  17.  
  18.     void Start()
  19.     {
  20.       moveRigibody = GetComponent();
  21.       transform = GetComponent();
  22.  
  23.     }
  24.  
  25.     void Update()
  26.     {
  27.         moveHorizontal = Input.GetAxis("Horizontal");
  28.         moveVertical = Input.GetAxis("Vertical");
  29.         print("체크");
  30.         characterRotation();
  31.     }
  32.  
  33.     void FixedUpdate()
  34.     {
  35.         moveHorizontal = Input.GetAxis("Horizontal");
  36.         moveVertical = Input.GetAxis("Vertical");
  37.         moveInput = new Vector3(moveHorizontal, 0, moveVertical);
  38.         moveRigibody.velocity = moveInput*speed;
  39.     }
  40.  
  41.     void characterRotation()
  42.     {
  43.         if (moveVertical > 0 && moveHorizontal < 0)
  44.         {
  45.            transform.rotation = Quaternion.Euler(0, -45, 0); // 위 좌
  46.         }
  47.         else if (moveVertical > 0 && moveHorizontal > 0)
  48.         {
  49.            transform.rotation = Quaternion.Euler(0, 45, 0); // 위 우
  50.         }
  51.         else if (moveVertical < 0 && moveHorizontal < 0)
  52.         {
  53.            transform.rotation = Quaternion.Euler(0, 225, 0); // 아래 좌
  54.         }
  55.         else if (moveVertical < 0 && moveHorizontal > 0)
  56.         {
  57.            transform.rotation = Quaternion.Euler(0, 135, 0); // 아래 우
  58.         } 
  59.         else if (moveVertical > 0)
  60.         {
  61.            transform.rotation = Quaternion.Euler(0, 0, 0); //위
  62.         }
  63.         else if (moveVertical < 0)
  64.         {
  65.            transform.rotation = Quaternion.Euler(0, 180, 0);//아래
  66.         }
  67.         else if (moveHorizontal < 0)
  68.         {
  69.            transform.rotation = Quaternion.Euler(0, -90, 0);//좌
  70.         }
  71.         else if (moveHorizontal > 0)
  72.         {
  73.            transform.rotation = Quaternion.Euler(0, 90, 0);//우
  74.         }
  75.     }
  76.  }
마우스와 오브젝트의 각도차이 구하고 적용

 


float GetRotationAngleByTargetPosition(Vector3 mousePosition) {
	// 캡슐의 위치를 스크린 좌표로 받아온다.
	Vector3 selfScreenPoint = Camera.main.WorldToScreenPoint(capsule.transform.position);
	//캡슐의 위치와 마우스 클릭 위치의 좌표 차이
	Vector3 diff = mousePosition - selfScreenPoint;
	
	//아크 탄젠트로 구한 라디안을 Mathf.Rad2Deg를 통하여 도수법(각도)으로 바꿔주기
	float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
	Debug.Log (string.Format("angle: {0:f}", angle));
	//최종각도 구하기.
	float finalAngle = angle - 90f;
	Debug.Log (string.Format("finalAngle: {0:f}", finalAngle));
	return finalAngle;
}
    
//선형 보간 기법으로 360도를 넘는 각도를 고려하는 LerpAngle 사용
capsule.transform.eulerAngles
	= new Vector3(0, 0, Mathf.LerpAngle(capsule.transform.eulerAngles.z, targetAngle, Time.deltaTime * capsuleRotationSpeed));

 

Sin을 활용하여 튕기는 공 구현
sphere.transform.position = new Vector3(
	sphere.transform.position.x + (capsule.transform.position.x - sphere.transform.position.x) * Time.deltaTime * sphereMagnitudeX,
	Mathf.Abs(Mathf.Sin ((Time.time - buttonDownTime) * (Mathf.PI * 2) * sphereFrequency) * sphereMagnitudeY),
	0
);

 

반응형