先在物体上挂载碰撞器,我用的是2D的,所以挂的是2D碰撞器
然后控制物体移动采用AddForce方式加力,具体代码如下:
void FixedUpdate()
{
//移动玩家
move(MoveJoystick.CurrentAxis);
}
public void move(Vector2 vec)
{
Vector2 motion = vec * MaxSpeed;
if (motion != Vector2.zero)
{
playerRigidbody.AddForce(motion, ForceMode2D.Force);
}
if (playerRigidbody.velocity.magnitude > MaxSpeed)
{
playerRigidbody.velocity = playerRigidbody.velocity.normalized * MaxSpeed;
}
}
//进入碰撞事件
void OnCollisionEnter2D(Collision2D collision)
{
Vector2 pos = collision.transform.position;
Vector2 m_forceHit = new Vector2(-pos.normalized.x, -pos.normalized.y) * 10;
playerRigidbody.AddForce(m_forceHit, ForceMode2D.Force);
}