unity move left and right
public float speed = 0.2f
transform.position = new Vector3(transform.position.x+speed,
transform.position.y, transform.position.z);
unity move left and right
public float speed = 0.2f
transform.position = new Vector3(transform.position.x+speed,
transform.position.y, transform.position.z);
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>(); //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
}
}
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us