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.
Source Code Used in This Video
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;
}
}
To download all of the assets for the entire project, click here.