Basic movement in Unity3D

How to create Basic Movement in Unity3D using C# code.

 

So we got our player Object:

And we want to make it move.

How we do it?

Let’s start with simple left and right movement on 2D space. We want to move our character for example on the X axis.

using UnityEngine;

public class PlayerController : MonoBehaviour {

    Rigidbody rb;
    public float speed = 10.0f;

    void Start () {
        rb = GetComponent<Rigidbody>();
    }

  void Update () {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            rb.velocity = transform.right * speed;
        }
    }
}

Here is the code for moving right if we press the Right Arrow Key.

But wait a second! We did move left after the second press while we wanted to move only right!? It’s because after we moved right the ball rotated and the Vector point for moving right was pointed in the other direction.

We can fix it when we add

rb.freezeRotation = true;

to our start function.

So after changing the speed to 2.0f and adding the code above we get something likes this:

Looks not that bad. Could be better, but we are just starting.

We want now implement movement to the left. We can just copy our function and change some things so we can move to the left.

using UnityEngine;

public class PlayerController : MonoBehaviour {

    Rigidbody rb;
    public float speed = 2.0f;

    void Start () {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

  void Update () {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            rb.velocity = transform.right * speed;
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            rb.velocity = -transform.right * speed;
        }
    }
}

There is not such function as transform.left so we need to mirror the transform.right function using the minus symbol.

This way we achieved movment left and right.

If we want to add other dimension to our movement and make it really 3D we can add the Z Axis to our code.

Because there is no shortcut for our transform function, we need to call our Vector3 Function directly.

For moving up, we can write something like this:

rb.velocity = new Vector3(0, 0, 1) * speed;

It does the same thing like the one above, but calls additionaly Vector3.

And here is the full code:

using UnityEngine;

public class PlayerController : MonoBehaviour {

    Rigidbody rb;
    public float speed = 2.0f;

    void Start () {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

  void Update () {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            rb.velocity = transform.right * speed;
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            rb.velocity = -transform.right * speed;
        }

        if (Input.GetKey(KeyCode.UpArrow))
        {
            rb.velocity = new Vector3(0, 0, 1) * speed;
        }

        if (Input.GetKey(KeyCode.DownArrow))
        {
            rb.velocity = new Vector3(0, 0, -1) * speed;
        }
    }
}

But is it the only way in which we can move our character? Well… Not really. It’s just the way using the transform function.

If we want to make our ball to move in more realistic way we can do it using the Input.GetAxis() function. This way we are using physics forces which give more realistic feeling.

using UnityEngine;

public class PlayerController : MonoBehaviour {

    Rigidbody rb;
    public float speed = 2.0f;

    void Start () {
        rb = GetComponent<Rigidbody>();
    }

  void Update () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        rb.AddForce(new Vector3(moveHorizontal, 0.0f, moveVertical) * speed);
    }
}

It’s based on Rigidbody, so changing the mass or Drag in the Rigidbody element throught Inspector is going to have impact on our Player Object.

Other way to create player Movement is to give the player Speed with ArrowUp/ArrowDown Key and steer it with ArrowLeft/ArrowRight Key.

using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float movementSpeed = 5.0f;
    public float rotationSpeed = 200.0f;

    void Update () {
        transform.Rotate(0, Input.GetAxis("Horizontal") * Time.deltaTime * rotationSpeed, 0);
        transform.Translate(0, 0, Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed);
    }
}

As you see we combined the first two possible solutions for movement and created a new one.

We used the transform function and Input.GetAxis()  to get our new possible movement. Other than that, this type of movement is great for Racing games.

Other than that, we can use the built-in solution which is provided by Unity. The Character Controller:

And here is the code for Character Controller which enables us to move our character with WASD or Arrow Keys.

using UnityEngine;

public class PlayerController : MonoBehaviour {


    CharacterController characterController;
    public float movementSpeed = 5.0f;
    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        characterController = GetComponent<CharacterController>();

    }
    void Update () {
        if (characterController.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            moveDirection = moveDirection * movementSpeed;
        }

        //Gravity
        moveDirection.y -= 10f * Time.deltaTime;

        characterController.Move(moveDirection * Time.deltaTime);
    }
}

We don’t use Rigidbody so we need to implement gravitation by ourselves.

That’s all for today. I hope you learned something about Unity Character Movement.

If you want to check more, you can look up on my Jumping tutorial:

How to make the player Object Jump in Unity 3D.

Or the Countdown timer tutorial:

How to create a simple countdown Timer in Unity

 

How to make the player Object Jump in Unity 3D.

How to make the player Object Jump when we press Space button on our Keyboard.

For Example, we got our player Object. The player Object ist just a simple Sphere Object with Red material on it.

If we add this Script to our Object, we make it Jump within pressing on the Space Button.

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour {

    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(new Vector3(0, 10, 0), ForceMode.Impulse);
        }
    }
}

We add 10 Points of Force (on the Y axis) to our Rigidbody Function. We do it with Vector3 and ForceMode.Impulse function.

The problem is we can do multiple Jumps at the same time. When we change the Value of 10 to 5 and press the space button multiple time we get something like this.

It’s not that bad actually… but if you didn’t planned to implement this in your project then you need to ground the player Object.

We can do it when we add “isGrounded” to our if operation as bool value and set the value to true in the void function OnCollisionStay()

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour {

    public bool isGrounded;
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnCollisionStay()
    {
        isGrounded = true;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
            isGrounded = false;
        }
    }
}

This way we can do a double jump:

But if your goal was that the player got only the possiblity to do a single jump than you need to replace the OnCollisionStay() function with OnCollisionEnter() function and tag your ground object with “Ground” as tag name.

Final Script for Single Jump:

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour {

    public bool isGrounded;
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == ("Ground") && isGrounded == false)
        {
            isGrounded = true;
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
            isGrounded = false;
        }
    }
}

This way we achived the possible solutions for making the player jump.

Other things which we can do is making the jump variable public and have more “space” for modifying our jumping behavior. Or we do it with other buttons or key press.

So if we want to make the player jump with our left mouse button click or while touching the mobile screen (if we plan to release it on android) we can write it this way:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0) && isGrounded)
    {
        rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
        isGrounded = false;
    }
}

And if we want to modify the speed of the player jumping we can write it this way:

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour {

    public float jumpSpeed = 5f;
    public bool isGrounded;
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == ("Ground") && isGrounded == false)
        {
            isGrounded = true;
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0) && isGrounded)
        {
            rb.AddForce(new Vector3(0, 2, 0) * jumpSpeed, ForceMode.Impulse);
            isGrounded = false;
        }
    }
}

This way we can modify the speed throught inspector too!

Other posts on the Unity3D topic:

How to create a simple countdown Timer in Unity

Tutorial: How to access variable from other class in Unity

OpenAI Retro Contest – Everything I know about JERK agent

The first approach in the OpenAI Retro Contest which I started to implement, test and modify was the JERK approach. Jerk agent is one of the baseline scripts for this contest.

You can find it here: https://github.com/openai/retro-baselines

I think it is the easiest algorithm to understand for programmers who doesn’t have any Machine Learning experience.

The pseudo-code for the JERK algorithm looks like this:

Why is this the easiest approach? Because this algorithm is based on rewards. But not the same kind of rewards like rainbow or ppo2. JERK algorithm has the moves already scripted before. It doesn’t learn the same way like the two others. Sonic runs forward and jumps and if it scores points or progresses on the level further it gets rewarded. It learns based on rewards and tries to not make the mistakes again, because making a mistake will cost him “reward points”. It’s somehow like with us, humans. We are motivated to do something if we get a possible reward at the end.

Read More

Tutorial: How to access variable from other class in Unity

I have dealt with this problem very often.

How to get variables from other Class in Unity? For example I’ve got one Class with public Variables and i want to get the same value of the Variable in other Class.

For Example it could be a Class which adds points to overall Score. But in other Class i show it using Unity UI System as Text.

Here is the Class with Variable which is calling the Function in other Class.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Score : MonoBehaviour {

  public GameObject scoreScript;
  // Use this for initialization

  public void OnTriggerEnter2D(Collider2D node)
  {
    if (node.gameObject.tag == "Apple") {
      Destroy (node.gameObject);
      ScoreMenager scorePointsScript =  scoreScript.GetComponent<ScoreMenager>();
      scorePointsScript.AddScore ();

    }
  }
}

 

And here is the Class which contains the Function where the variable points gets incremented.

using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class ScoreMenager : MonoBehaviour {
  public int points;


  Text text;

  void Awake ()
  {
    text = GetComponent<Text> ();

  }
  // Use this for initialization
  void Start () {
  }

  public void AddScore()
  {
    points++;
  }
  // Update is called once per frame
  void Update () {
    

    text.text = "Score: " + points;
  }
}

 

Don’t Forget to Add The “Score” Script to your character! And the same for ScoreMenager, which needs to be added to the UI Element.

And also don’t forget to Create the Text as GUI

Also important is the fact, that you need to change the “Tag” of your element which will be destroyed. After it increases the Score Points value.

Component > UI > Text

 

Other tutorials in the series:

How to make the objects fall in Unity

Making Objects Fall Random On The Screen in Unity

How to Speed Up (Increase Speed) Time in Unity

How to create a simple countdown Timer in Unity

Rendering Crisp Pixelart in Phaser (2017)

I had this problem while building my pixelart game in Phaser. My Pixelart was blurry. It didn’t looked nice. I was searching the web for an answer but i didn’t found one. Many of the tutorials were outdated so i decided to write my solution here.

You can find the working example here: http://www.noob-programmer.com/pixelart_example/

Example above works for Chrome and Mozilla Firefox.

Solution includes editing CSS and one line in phaser script.

Here is the CSS which you need to apply to your html element:

body {
  filter: none;
  image-rendering: -moz-crisp-edges;
  image-rendering: -webkit-crisp-edges;
  image-rendering: pixelated;
  image-rendering: crisp-edges;
}

Used it on body element.

The other line is the Phaser script:
var game = new Phaser.Game(200, 150, Phaser.AUTO, 'gameContainer', {
      preload: preload,
      create: create,
      update: update
    }, null, false, false);

The last parameter (“false”) is for antialiasing. It needs to be set to false.

What about other browsers? What do i need to change in order to get crispy Pixelart? Check this solution:

body {
  -ms-interpolation-mode: nearest-neighbor; // IE 7+ (non-standard property)
  image-rendering: -webkit-optimize-contrast; // Safari 6, UC Browser 9.9
  image-rendering: -webkit-crisp-edges; // Safari 7+
  image-rendering: -moz-crisp-edges; // Firefox 3.6+
  image-rendering: -o-crisp-edges; // Opera 12
  image-rendering: pixelated; // Chrome 41+ and Opera 26+
}

Source: https://builtvisible.com/image-scaling-in-css/

Source: https://developer.mozilla.org/en-US/docs/Games/Techniques/Crisp_pixel_art_look

Poradnik: Jak skonfigurować konto git z GitLab.

Ze względu tworzenia projektów na studia i konieczności używania systemu git zostałem zmuszony porzucić na jakiś czas GitHuba i zacząć używać GitLaba.

Powód?

Prywatne repozytoria.

Każdy z nas dostaje co tydzień szereg zadań programistycznych, które musi wykonać. Samemu, bądź z partnerem w grupie. Ze znanych dostępnych mi serwisów oferujących prywatne repozytoria należą wcześniej wymieniony GitLab oraz Bitbucket. Bitbucekt jednak oferuje ograniczenie do 5 członków. Co jednak pasuje, ale jednak ze względu na to, że słyszałem wiele dobrego o GitLabie to postanowiłem go wypróbować.

Read More