티스토리 뷰

오늘은 Unity에서 가장 많이 사용되는 오브젝트 이동과 관련된 내용을 정리해 보겠다.


Unity에서 물체를 이동시키는 방법은 여러가지 있겠지만 크게 3가지 종류로 나뉠수 있을 것 같다.

  • 키보드 방향키로 이동
  • 마우스 클릭한 곳으로 이동
  • 마우스로 드래그


각각의 이동을 구현하기 위해 필요한 내용들을 말로 풀어보았다

키보드로 이동 1. 키마다 방향을 할당한다.
2. 특정 키가 눌러졌을때, 정해진 방향으로 object의 위치를 이동
클릭한 곳으로 이동 1. 클릭한 때, 클릭한 곳의 위치를 안다
2. 클릭한 위치로 object를 이동시킨다.
드래그 1. 클릭시 1)클릭한 좌표와 2)오브젝트 중앙 자표와의 차이 (offset)를 확인
2. 드래그할때 오브젝트의 위치를 → 클릭좌표 + offset 으로 이동

각 이동의 구현과 관련된 함수 및 변수를 적어 보았다.

키보드 이동하기

[3d인 경우]

조작정보 받기 위치정보 확인 및 변수선언 이동
GetAxis("Horizontal")
GetAxis("Vertical")
GetKeyButtonDown()
GetKey()
v = Input.GetAxisRaw("Vertical");
h = Input.GetAxisRaw("Horizontal");
float speed = 숫자;

transform.position +=
new Vector3(h, 0, v) * Speed * Time.deltaTime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    float h;
    float v;
    float speed = 2f;

    void FixedUpdate()
    {
       v = Input.GetAxisRaw("Vertical"); // 위아래에 해당하는 키보드가 눌릴때 숫자(-1,0,1) 반환
       h = Input.GetAxisRaw("Horizontal"); // 왼쪽오른쪽에 해당하는 키보드가 눌릴때 숫자(-1,0,1) 반환
       
       //object의 위치를 눌린 입력받은 값에 따라 이동
       transform.position += new Vector3(h, 0f, v) * speed * Time.deltaTime;
    }
}


[2d인 경우]

조작정보 받기 위치정보 확인 및 변수선언 이동
GetAxis("Horizontal")
GetAxis("Vertical")
GetKeyButtonDown()
GetKey()
Vector2 move = New Vector2();

move.x = Input.GetAxisRaw("Vertical");
move.y = Input.GetAxisRaw("Horizontal");

move.Normalize(); //
Rigidbody2D rb;
float speed = 숫자;

rb = Get Component<Rigidbody2D>(); }

rb.velocity = move * speed }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    float speed = 2f;
    Vector2 move = new Vector2(); // 새로운 Vector2 객체 생성
    Rigidbody2D rd2D; // Rigidbody2D 객체 생성

    void start(){
    	rd2D = GetComponent<Rigidbody2D>()// rd2D의 현재 스크립트가 삽입된 object의 Rigidbody2D 불러오기
    }

    void FixedUpdate()
    {
    	move.x = Input.GetAxisRaw("Horizontal");
        move.y = Input.GetAxisRaw("Vertical");
        move.Normalize();// 이동방향에 상관없이 일정한 속도 유지
        rd2D.velocity = move * speed;
    }
}


클릭한 곳으로 이동하기

조작정보 받기 위치정보확인 이동
OnMouseDown() cam.ScreenToWorldPoint(Input.mousPosition); transform.position =
Vector3.MoveToward (시작점, 도착점, 속도)

[2D에서 이동할때]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveToClick : MonoBehavior {
	private Camera cam;
	[SerializeField] private speed = 10f;
    
    void Awake(){
    	//카메라를 이렇게 따로 지정해주는 이유 = 찾아놓고 계속 쓰기 위해(코드가 가벼워짐)
    	cam = Camera.main;
    }

    #클릭 했을때
    void OnMouseDown(){
    	GetMousePos()
        
        //오브젝트 이동
        transform.position = Vector3.MoveTowards(transform.position, 
                                                 GetMousePos(), 
                                                 speed*Time.deltaTime)
    }
    
    #마우스의 위치값 가져오기
    Vector3 GetMousePos(){
        var mousePos = cam.ScreenToWorldPoint(Input.mousPosition);
        mousePos.z = 0; 
        return mousePos; // 마우스 위치값 반환 
    }
}

3d


드래그&드롭 (2d)
자세한 내용은 이전에 만들어 놓은 포스터를 확인
https://justdoitman.tistory.com/207

 

(C#) UNITY_게임 오브젝트 옮기기(드래그앤드랍)

오늘은 Unity에서 게임 오브젝트를 클릭 해서 옮길 수 있는 Drag&Drop에 대해서 배워볼 예정이다 1. OnMouseDrag를 이용해 기본적인 Drag & Drop 기능 구현 기본적인 기능 구현에 앞서서, object에 'collider2D' c.

justdoitman.tistory.com

조작정보 받기 위치정보확인 이동
OnMouseDown()
OnMouseDrag()
cam.ScreenToWorldPoint(Input.mousPosition);
Vector3 offset = object.position - mouse.position
transform.position = mousePos;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragAndDrop : MonoBehavior {
	private Camera cam;
	private Vector3 dragOffset; // 클릭했을때, object의 중앙좌표와과 클릭한 좌표사이의 차이
    
    void Awake(){
    	//카메라를 이렇게 따로 지정해주는 이유 = 찾아놓고 계속 쓰기 위해(코드가 가벼워짐)
    	cam = Camera.main;
    }


    #클릭 했을때
    void OnMouseDown(){
    	dragOffset = transform.position - GetMousePos(); 
        //object의 중앙좌표와과 클릭한 좌표사이의 차이값을 구하기
    }
    
    #드래그를 하는 동안
    void OnMouseDrag(){
    	transfrom.position = GetMousePos() + dragOffset; 
        //object의 위치를 마우스 위치에 중앙좌표 차이만큼 더한곳으로 옮기기
    }
    
    Vector3 GetMousePos(){
        var mousePos = cam.ScreenToWorldPoint(Input.mousPosition);
        // 마우스의 위치값 가져오기
        mousePos.z = 0; 
        return mousePos; // 마우스 위치값 반환 
    }
}

참고사이트
https://www.youtube.com/watch?v=cvI25BDJPAA

 

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함