유니티/프로젝트정리
유니티 2D 움직임, AddForce와 velocity 중 어떤게 적당한가
KFRI
2024. 4. 30. 10:57
※물리연산이기에fixed update에서 작동
1.<Rigidbody2D>().AddForce사용
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
//move ,jump ,stop idle
public float jumpPower = 10;
public float speed = 10;
Rigidbody2D cRb;//component RigidBody(최상위 Rigidbody가진 오브젝트 이름:.component)
void Awake()
{
cRb = GetComponentInParent<Rigidbody2D>();
}
void FixedUpdate()
{//문제: AddForce사용시 방향전환시 반대힘이 같이 가해져 움직임이 무거운느낌이듬
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponentInParent<Rigidbody2D>().AddForce(new Vector2(0, jumpPower));
}
if (Input.GetAxis("Horizontal") != 0)
{
GetComponentInParent<Rigidbody2D>().AddForce(new Vector2(Input.GetAxis("Horizontal") * speed, 0));
}
}
}
결과:키방향전환시 바로 바뀌지않고 힘을 받은방향으로 밀려났다가 둔탁하게 움직임
동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.
판정:비적합
2.< Rigidbody2D>().velocity = new Vector2(GetComponent< Rigidbody2D>().velocity.x, jumpPower*Time.deltaTime)사용
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
//move ,jump ,stop idle
public float jumpPower = 10;
public float speed = 10;
Rigidbody2D cRb;//component RigidBody(최상위 Rigidbody가진 오브젝트 이름:.component)
void Awake()
{
cRb = GetComponentInParent<Rigidbody2D>();
}
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Space))
{
cRb.velocity = new Vector2(cRb.velocity.x, jumpPower*Time.deltaTime);//속도값을 반영하여 낙하
}
if (Input.GetAxis("Horizontal") != 0)
{
cRb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed , cRb.velocity.y);// y값. 변동반영
}
}
}
결과: 키를 누르지않으면 속도가0이기 떄문에 키방향 전환이 빠르고 자연스러움
동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.
판정 :적합