Variable Jump Height in Unity

Standard

In numerous games, characters have variable jump height. What this means is that the more your press the jump button, the more the character will remain in the air, or even jump a little higher ( think super mario games ). In this tutorial, I’ll show you a simple way to implement this kind of jumping in your games.

You can begin by making a new project, or create a new scene from a project you have in Unity. Add a cube to the scene to act as the ground, so you might want to scale it forward (z) and sideways (x), and finally add another cube to act as our player. By default, both of these will have BoxCollider Components attached to them, which is good, but our player will also need a Rigidbody Component, so we can use Unity’s physics engine. Note that if you add a Rigidbody component to the ground, make sure you have IsKinematic enabled and Gravity disabled, so it does not fall. On the contrary, make sure the player has Gravity enabled and IsKinematic disabled ( those should be set by default ). You should now have something pretty simple such as:
Screen Shot 2015-07-23 at 21.29.55

So, using Unity’s physics engine, how can we make our player jump? By looking at the Rigidbody’s documentation, we can see that we have many methods to add force, and we’ll use the normal AddForce, which takes a directional vector and a force mode. As far as direction goes, we’ll want the player to jump up, so we can use the local up vector from the player’s transform. For the ForceMode, we have Force, Acceleration, Impulse, and VelocityChange, and I will use VelocityChange for now.

In order to control how much I want my player to jump I need to setup some variables first, namely, I will need a jumpVelocityChange and isJumping variable. I will also store the reference to the rigidbody, that I will get in the Awake method.

Quick Tip: [SerializeField] is used in unity, not only but also, to expose private variables in the Inspector. Why don’t I just make it public you ask? Because I don’t want other classes to access those variables, they are meant to be private.

So now that I have those setup, I’ll set them on the Inspector. I chose to set _jumpVelocityChange to 50 to begin with and _isJumping variable to false. Now since we’re using the physics engine, we should apply our changes in the FixedUpdate and not in the Update method by default. Meaning that we will not need to multiply our force values by Time.deltaTime, since FixedUpdate always ticks at the same rate.

Now, to make the actual jump. In our Update function, I’m going to check if I click the left mouse button. If the left mouse button is pressed and I am not currently jumping, I’ll set the _isJumping variable to true, and add a vertical force to the player’s rigidbody.

This only will make the player jump when you click the left mouse button. But now when it falls down, you can’t jump again. Care to guess why? Because we haven’t set our _isJumping variable to false. So when should we do that? I’m going to go pretty simple with this, since both the ground and the player have colliders and rigidbodies, I can call the OnCollisionEnter method from my player, and when it’s called, switch the variable to false. I’m not going to add anything else now, and leave it like this, but ideally, you’ll want to check with whom the collision was made, if indeed it was the floor, for instance.

Now everything seems to work fine. You can jump, fall down, and then jump again. But what about the SuperMario style jump? You know, the more you press, the longer you remain in the air? For this, I need to setup three new variables, _startJumpTime, _maxJumpTime and _jumpAcceleration, so I can control air time and the acceleration force added during the jump.

I’ve changed the update method to include the “hold-to-jump-higher-and-for-more-time” behaviour, and updated the first impulse to add the start jump time. So your FixedUpdate method should look something like this:

This checks for a different Input method, GetMouseButton instead of GetMouseButtonDown. The first one is called whenever the button is down, and the later is called once, when the button was pressed. So we capture the long button press, check if we are indeed already jumping, and check the amount of time we have to allow this long jump. If all those conditions are met, we keep on jumping, giving a continuous acceleration. This time we use an acceleration instead of velocity change, so the effects is a lot smaller.

So now you should be able to have your awesome “Super Mario style Jump”:

Quick Tip: Notice the [RequireComponent (typeof(RigidBody))] on the top of the class. What this does is automatically add the RigidBody component to the object you are adding this class to. So if there is no rigidbody, it will automatically add it. This makes sure that whenever I call the component in the Awake method, I always get a rigidbody, thus avoiding future errors.

Here’s the final result for my game:

How to create a recursive call with Unity’s Coroutines

Standard

During the development of Super Stems I’ve had to deal with chain reaction. I started a battle with one tile, and if they win, the captured tile would start a battle, and this would happen recursively. For some reason, I have this battle method call on a different thread, in Unity’s terms, a Coroutine.

Now comes the question. How do I handle recursion with Coroutines? After looking around the doc and experimenting, I found a solution.

Here’s a sample code on how to make it work.

After calling the entry point to your recursive method StartBattle, inside, you have yield return a new Coroutine call to the recursive method. This way, the execution order will be correct. Try it out and see for yourself.

Output should be.

Enjoy

Simple Achievement System in C#

Standard

Achievements are becoming more and more usual in games. They provide the player a sense of accomplishment and progress by rewarding them with badges that proves their skill and experience. Some achievements are simple and other require a combination of particular actions to unlock. In this article I show you how to make a simple Achievement System using C# and will demonstrate it using Unity3D, but this should be easy enough for you to port it to whatever language you’re more familiar with for your games.

Continue reading

Non Blocking C# Task Cancelling

Standard

In our previous sample snippet, Cancel a Loop in a Task with CancellationTokens in c# , I try to explain how we can get out of a looping c# task, but a problem may arise from that situation. If we were to wait for any result out of that Task, we would be blocking the calling thread until the task returned, which is not good if we are on the main thread. We would locking our UI and might crash our application.

So I’ve been testing different ways to get out of that loop without causing any trouble, and you can achieve what we want many different ways.

So, to begin with, I think I would correctly assume that it is only necessary to wait for a task to complete if that task will return something. If there is no return value, why would we want to call wait on it? We can just break out of it, correct me if I’m wrong. If we have a return value, then it is necessary to surround the wait call on the task with try/catch to receive its result. But then again, we can avoid the locking here with a continuation task, which will create and start the task after the first one completes, giving us the result from the previous task to work with.

Continue reading

Cancel a Loop in a Task with CancellationTokens in C#

Standard

This post explains the use of Cancellation Token in C# using Tasks, which are available since .Net Framework 4.

Say you’ve created a asynchronous Task. The method you’re running inside your task contains a loop ( infinite or not ), and you want to break out of it peacefully. You would need to create a CancellationTokenSource and pass a Cancellation Token to the Task so it can be accessed in the main loop. Continue reading