I am working on a 2d game movement, in which i want my character to move according to the slope angle, like this:
but while press move …it end up like this
every time when i press move, the the rotation in z axis resets to 0… iam stuck in this problem for a day now. pls help me figure it out as iam starting to learn unity
my code:
void Start()
{
_rb = GetComponent<Rigidbody2D>();
if(_rb == null)
{
Debug.LogError("The RigidBody2D is NULL");
}
_Anim = GetComponent<Animator>();
if(_Anim == null)
{
Debug.LogError("The Animator is NULL");
}
}
void Update()
{
RaycastHit2D[] hits = new RaycastHit2D[2];
int h = Physics2D.RaycastNonAlloc(transform.position, -Vector2.up, hits);
if (h > 1)
{
//Debug.Log(hits[1].normal);
angle = Mathf.Abs(Mathf.Atan2(hits[1].normal.x, hits[1].normal.y) * Mathf.Rad2Deg);
Debug.Log(angle);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, angle);
}
if (MoveInput > 0 )
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
else if(MoveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
IsGrounded = Physics2D.OverlapCircle(FeetPos.position, CircleRad, WhatIsGround);
if (IsGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
_Anim.SetTrigger("TakeOff");
_rb.velocity = Vector2.up * JumpForce;
}
if(IsGrounded == false)
{
_Anim.SetBool("IsJumping", true);
}
else
{
_Anim.SetBool("IsJumping", false);
}
}
private void FixedUpdate()
{
MoveInput = Input.GetAxis("Horizontal");
_rb.velocity = new Vector2 (MoveInput * Speed, _rb.velocity.y);
if(MoveInput != 0)
{
_Anim.SetBool("IsMoving", true);
}
else
{
_Anim.SetBool("IsMoving", false);
}
}
}
pls ignore my messy coding as iam a beginner…and thank u in advance
,