How to get a character to move left and right in Unity 2D. code example
Example: How to get a character to move left and right in Unity 2D.
//C# Unity2D
//I wrote this and I'm quite new to Unity and C# so it could probobally be improved.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemymovement : MonoBehaviour
{
private float ogpos; //Original Position of the enemy
public int distance; //How far we want to move in each direction
private bool going; //Says if we are going left or right
private float npos; //Our negative destination
private float ppos; //Our positive destination
private Rigidbody2D rb; //RigidBody2D
void Start()
{
going=true;
rb=GetComponent(); //RigidBody2D
ogpos=transform.position.x; //We do this to get the position it started in. This is only the x along with ppos and npos
npos=ogpos-distance; //Subtract from ogpos for the positive destination
ppos=ogpos+distance; //Add to ogpos for positive destination
}
void Update()
{
//Check if we are going right or left, true being right.
if(going==true){
rb.velocity = new Vector2(1,rb.velocity.y); // Add to go right The 1 is the speed
//Check if it's equal to or greater than our positive destination
if(transform.position.x>=ppos){
going=false; //Swap going
}
}
if(going==false){
rb.velocity = new Vector2(-1,rb.velocity.y); //Subtract to go left
//Check if it's equal to or less than our negative destination
if(transform.position.x<=npos){
going=true; //Swap going the negative one is its speed so if it was a variable multiply by negative 1
}
}
}
}