I am making a 2d game in which the character falls on a slope and rotates while falling with a fixed rotation. When touching the ground the character jumps at an angle relative to the slope. I want it to always jump towards the orientation of itself, meaning towards his head, no matter what orientation it has at the moment when it is touching the ground with its legs. I attached a picture to make myself more understandable, and my code so far. I am new to unity and I hope you can help me with this problem. Thank you very much!
private void FixedUpdate()
{
IsTouchingGround = Physics2D.OverlapCircle(groundCheckPoint.position, groundCheckRadius, GroundLayer);
if (IsTouchingGround)
{
rigidBody.velocity = new Vector2(rigidBody.velocity.x, JumpPower);
}
CodePudding user response:
assuming it is a Rigibody2D
I would just do e.g.
rigidBody.velocity = Quaternion.Euler(0, 0, rigidbody.rotation) * Vector2.up * JumpPower;
or basically this about equals using
rigidBody.velocity = transform.up * JumpPower;
so no need / use of maintaining the X
velocity and rotate the resulting vector by the current rotation.
CodePudding user response:
For this purpose, you must use Reflect
of velocity on the Normal
of ground. I suggest some changes in the code. You can use a raycast from the body of the object to the ground and find the point of impact. I will use this code as a guide for you.
private void Update()
{
// cast a ray from transform pos to ground, you can also use groundCheckPoint.position to this
var hit = Physics2D.Raycast(transform.position, Physics2D.gravity, rayLength, groundLayer.value);
// when any hit with ground detected
if (hit) rb.velocity = Vector2.Reflect(rb.velocity, hit.normal);
}