- Home /
Question by
arnoldkmwaura · May 15, 2018 at 12:18 PM ·
2d character
,How do you make a 2d character move constantly and also change direction
How do you make a 2d character move constantly and also change direction ,
Comment
Answer by BGOKMEN14 · May 15, 2018 at 12:35 PM
Hello @arnoldkmwaura!
This code will make the character move constantly to the right and when space is pressed, it will start constantly moving up:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moveConstantly : MonoBehaviour {
Vector2 moveForward;
bool canGoForward = true;
bool canGoOtherDirection;
void Update () {
if (canGoForward) {
moveForward = gameObject.transform.position; //When the game starts it will start to go to the right
moveForward.x += 0.1f;
gameObject.transform.position = moveForward;
}
if (canGoOtherDirection)
{
moveForward.y += 0.1f;
gameObject.transform.position = moveForward;
}
if (Input.GetKey (KeyCode.Space)) //When space is pressed, it will start to go up
{
canGoForward = false;
canGoOtherDirection = true;
}
}
}
I HOPE THIS HELPS!
Thanks,can you also use it to make it move to the left
Yes to make it move to the left simply type this code:
moveForward.x -= 0.1f;
gameObject.transform.position = moveForward;
To make it go down simply type this code:
moveForward.y -= 0.1f;
gameObject.transform.position = moveForward;
You should also to multiply by time.deltatime because the character is going to move 0.1 units every frame if you don't