Unity - Making simple 2D game part 1

Matthew·2024년 9월 6일
0

Making SimpleGame

목록 보기
1/1

Starting

  • I have simple movements for now, which is just moving, jumping.

    Goal is to implement wall jumping mechanic.

  • I think it might take a while to achieve wall jumps because it's quite complicated.
  • This post is about me going through trials & errors and record what I did.

How to Wall Jump

Steps

  1. Detect walls if the player is walking into the wall.
  2. If the player is not on the ground and pressing towards the wall, the player starts sliding down the wall.
  3. If the player is sliding down the wall, and the player is pressing jump button, force is applied on the opposite side of x value where the player is facing.

Write the code

  • I have to detect the wall first
public Transform wallCheck;
public LayerMask wallLayer;
	void Update()
    {
    	if(WallCheck())
        {
        	Debug.Log("Is wall");
        }
    }
	bool WallCheck()
    {
        return Physics2D.OverlapCircle(wallCheck.position, 0.2f, wallLayer);
    }
    
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(wallCheck.position, .2f);
    }

  • I did OnDrawGizmos() to visualize the Physics2D.OverlapCircle()
  • If the OverlapCircle() hits the wall layer, on the console it should say "Is wall".

Wall Slide

  • If the player is not on the ground, and pressing against the wall, it should slide down the wall.
void WallSlide()
    {
        if (!isGround && WallCheck() && h != 0f)
        {
            isWallSliding = true;
            rigid.velocity = new Vector2(rigid.velocity.x, Mathf.Clamp(rigid.velocity.y, -wallSlidingSpeed, float.MaxValue));
        }
    }

Mathf.Clamp() : Constrains a value within a specified range.

Mathf.Clamp(float value to be clamped, float min, float max)

The function returns

  • The original value if it's within the specified range.
  • The minimum value if the original value is less than the minimum.
  • The maximum value if the original value is greater than the maximum.
  • Mathf.Clamp() is used to prevent accelerating while sliding down the wall.
void WallSlide()
    {
        if (!isGround && WallCheck() && h != 0f)
        {
            isWallSliding = true;
            rigid.velocity = new Vector2(rigid.velocity.x, Mathf.Clamp(rigid.velocity.y, -wallSlidingSpeed, float.MaxValue));
        }
        else
        {
        	isWallSliding = false;
        }
    }
  • Lastly, else is isWallSliding = false;

profile
Growing Game Dev

1개의 댓글

comment-user-thumbnail
2024년 9월 13일

I’ve been hooked on Krunker io for weeks. The fast-paced action and variety of game modes keep me entertained. The pixel graphics are surprisingly effective, and the community content is a nice touch.

답글 달기