이동

2022. 6. 16. 22:27Unity/스크립트 기본

트랜스폼(직접 이동) + 벡터 - 벽으로 이동시 흔들리는 문제있음

void Update(){
    Vector3 moveVelocity = Vector3.zero;
    if(Input.GetAxisRaw("Horizontal") < 0){
      moveVelocity = Vector3.left;
    }
    else if(Input.GetAxisRaw("Horizontal") > 0){
      moveVelocity = Vector3.right;
    }
    transform.position += moveVelocity * 3 * Time.deltaTime;
}

트랜스폼(직접 이동) - 벽으로 이동시 흔들리는 문제있음

void Update(){
    if(Input.GetAxisRaw("Horizontal") < 0){
    	transform.Translate(Vector2.right * -2f * Time.deltaTime);
    }else if(Input.GetAxisRaw("Horizontal") > 0){
    	transform.Translate(Vector2.right * 2f * Time.deltaTime);
    }
}

리지드바디2D(물리적 이동) 애드포스(가속운동) - 가속이 엄청 돼서, 속도제한 걸어야 할 필요 있음. 점프구현에 좋음

// 변수 선언
Rigidbody2D rigid;
float h;

void Start(){ // 컴포넌트 불러오기
	rigid = gameObject.GetComponent<Rigidbody2D>();
}

void Update(){ // 입력 처리
	h = Input.GetAxisRaw("Horizontal");
}

void FixedUpdate(){ // 물리적인 처리
	rigid.AddForce(Vector2.right * h * 1, ForceMode2D.Impulse);
}

리지드바디2D(물리적 이동) 무브포지션 - 낙하중에 좌우로 연타하면 낙하속도가 느려지는 문제가 있음

Rigidbody2D rigid;
float h;

void Start(){
    rigid = gameObject.GetComponent<Rigidbody2D>();
}

void Update(){
   h =	Input.GetAxisRaw("Horizontal");
}

void FixedUpdate(){
    if(h<0){
        // -transform.right대신 Vector3.left 을 사용해도 됨. Vector3가 있는동안 transform.left는 존재하지 않음
        rigid.MovePosition(transform.position - transform.right * 5 * Time.deltaTime);
    }else if(h>0){
        rigid.MovePosition(transform.position + transform.right * 5 * Time.deltaTime);
    }
}

리지드바디2D(물리적 이동) 벨로시티(등속운동) - 그냥쓸경우 가장 괜찮음

Rigidbody2D rigid;
float h;

void Start(){
    rigid = gameObject.GetComponent<Rigidbody2D>();
}

void Update(){
    h =	Input.GetAxisRaw("Horizontal");
}

void FixedUpdate(){
	// 여기에 Time.deltaTime 안곱해도 되는가?
    rigid.velocity = new Vector2(h * 5f, rigid.velocity.y);
}

가속도 초기화

rigid.velocity = Vector2.zero;
rigid.velocity = new Vector2(rigid.velocity.x, 0);
728x90

'Unity > 스크립트 기본' 카테고리의 다른 글

킵입력  (0) 2022.06.16
타이머  (0) 2022.06.16
색변경  (0) 2022.06.16
좌우반전  (0) 2022.06.16
생명주기 함수  (0) 2022.06.16