Domanda

So, I'm starting a top-down 2D RPG sort of game, with free-form movement instead of, well, large-grid specific movement. I got a 'basic guy moving across the screen colliding with a tilemap'. However, when I hit a tile with a diagonal collider, I slow way down.

I seem to be doing this:

Wrong

When I should be doing this:

Right

My code is very simple and barebones. After scouring this on the internet for most of the day, I came up with this solution which doesn't work.

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxisRaw("Horizontal");
    float moveVertical = Input.GetAxisRaw("Vertical");

    Movement = new Vector2(moveHorizontal, moveVertical);
    Movement.Normalize();
    rigidbody2D.velocity = Movement * Speed;
}


void OnCollisionEnter2D(Collision2D other)
{
    Normal = other.contacts[0].normal;
    rigidbody2D.velocity -= Normal * Vector2.Dot(rigidbody2D.velocity, Normal);
}

What am I doing wrong? I imagine this is a relatively standard problem, as sliding along diagonals or slopes in platformers is quite common in games.

È stato utile?

Soluzione

I finally resolved this! My gut feeling was right: I was overthinking it.

Step 1: Remove all of the code example above and just have a simple:

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxisRaw("Horizontal");
    float moveVertical = Input.GetAxisRaw("Vertical");

    movement = new Vector2(moveHorizontal, moveVertical);
    movement.Normalize();
    rigidbody2D.velocity = movement * Speed;
} 

Step 2: In your assets folder, go to Create > Physics2DMaterial. Create one.

Step 3: Click your new material, and call it whatever you want. I called it "Frictionless". Set Friction to 0, and make sure "Bounce" is 0.

Step 4: Drag your new material to any of the "Physics Material (2D)" fields in any of the objects involved in the equation.

You're done!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top