0
\$\begingroup\$

I've written this C# code to handle movement in my testing project. The game is supposed to be 2D, some kind of a platformer, just to get me started with Unity. However, it seems there's something odd going on. The movement isn't particularly smooth (especially in Editor, it's a bit better when built and ran as .exe file) and jumping is very inconsistent, meaning sometimes it jumps to a certain height and sometimes it jumps ridiculously high. Seems random.

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    public float MaxSpeed = 10f;
    public float JumpForce = 700f;
    public Transform GroundCheck;
    public LayerMask WhatIsGround;

    bool facingRight = true;
    bool isOnGround = false;
    float groundRadius = 0.2f;

    void FixedUpdate()
    {
        isOnGround = Physics2D.OverlapCircle(GroundCheck.position, groundRadius, WhatIsGround);
        if (isOnGround && Input.GetAxis("Jump") > 0)
        {
            rigidbody2D.AddForce(new Vector2(0, JumpForce));
        }

        float move = Input.GetAxis("Horizontal") * MaxSpeed;
        rigidbody2D.velocity = new Vector2(move, rigidbody2D.velocity.y);

        if ((move < 0 && facingRight) || (move > 0 && !facingRight))
            Flip ();
    }

    void Flip()
    {
        Vector3 scale = transform.localScale;
        scale.x *= -1;
        transform.localScale = scale;

        facingRight = !facingRight;
    }
}

Can anyone tell me what's wrong? There are just two simple platforms and one character, everything done in 2D mode with 2D psychics. The funny thing is that every tutorial handles movement differently and as a beginner in game development I'm kinda baffled by it.

Oh, and the version of Unity is 4.5.3f3, if that changes anything... I'm considering trying the newest beta of 4.6 to see if it is any better, because they're bragging about the new GUI and better 2D physics.. Also, I'm using Windows 8.1.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's because of the variable IsOnGround and duration of jump key.

Imagine this, no matter how fast you are. Update will be called 60times a second. That makes jump key true for more than a instance. Also it takes player time to achieve lift off making isOnGround true for more than one instance . Hence the inconsistent jump, try switching isOnGround to off the instant he jumped in that if statement and switching it back on, like a second later.

P.S you can use a diff var to achieve that effect as well.

Platform games on physics engine will always be hard to perfect, its not unity's fault.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .