Moving Left & RightMr. Postman Video Tutorial Series - Part 2

This is the second part of the Mr. Postman series where I show you how to make a completed game in Unity 3D, using 2D sprites.

In this video, we discuss:

  • 0:22 - create UI buttons for visual "press down" effect
  • 2:20 - creating our movement script
  • 2:55 - setting up variables
  • 3:33 - writing our start function
  • 4:00 - while loop to detect mobile touches in Unity and their position on screen
  • 5:37 - writing our RunCharacter function
  • 7:48 - applying script to camera
  • 8:24 - keeping the character on screen
  • 11:10 - flipping the sprite to face the direction it is moving

Source Code Used in This Video

To download all of the assets for the entire project, click here.

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

public class Character : MonoBehaviour {
    //variables
    public float moveSpeed = 2500;
    public GameObject character;

    private Rigidbody2D characterBody;
    private float ScreenWidth;
    private float widthRel;

    // Use this for initialization
    void Start () {
        ScreenWidth = Screen.width;
        widthRel = character.transform.localScale.x / ScreenWidth;
        characterBody = character.GetComponent<Rigidbody2D> ();        
    }

    // Update is called once per frame
    void Update () {
        int i = 0;
        //loop over every touch found
        while (i < Input.touchCount) {
            if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
                //move right
                RunCharacter(1.0f);
            }
            if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
                //move left
                RunCharacter(-1.0f);
            }
            ++i;
        }
    }
    void FixedUpdate(){
        #if UNITY_EDITOR
        RunCharacter(Input.GetAxis("Horizontal"));
        #endif

        Vector3 viewPos = Camera.main.WorldToViewportPoint (character.transform.position);
        viewPos.x = Mathf.Clamp (viewPos.x, widthRel, 1 - widthRel);
        character.transform.position = Camera.main.ViewportToWorldPoint (viewPos);
    }
    private void RunCharacter(float horizontalInput){
        //move player
        characterBody.AddForce (new Vector2 (horizontalInput * moveSpeed * Time.deltaTime, 0));

        //turn character around
        Vector3 newScale = characterBody.transform.localScale;
        if (horizontalInput != 0) {
            newScale.x = horizontalInput < 0 ? -1 : 1;
        }
        characterBody.transform.localScale = newScale;
    }

}

 

LINK TO THIS POST

SHARE THIS POST


DISCUSSION