- Home /
Why doesn't my object move left?
So I have an object that isn't controlled by the player that I want to move left and right randomly at intervals. I wrote this script and it works somewhat except my object never moves to the right... I'm going mad trying to figure out why. I'm sure I'm missing something very obvious.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OttoMoveAI : MonoBehaviour
{
public float moveSpeed = 100f;
private Rigidbody2D rb;
Animator anim;
SpriteRenderer sP;
public GameObject otto;
bool moveRight;
bool moveLeft;
bool stayStill;
private int randomNum;
private int directionNumR;
private int directionNumL;
private Vector2 right;
private Vector2 left;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
sP = gameObject.GetComponent<SpriteRenderer>();
stayStill = true;
}
// Update is called once per frame
void Update()
{
// directionNumR = Random.Range(0, 2);
// directionNumL = Random.Range(0, -2);
randomNum = Random.Range(1, 10);
if (randomNum == 2)
{
moveRight = true;
moveLeft = false;
stayStill = false;
}
if
(randomNum == 3)
{
moveRight = false;
moveLeft = true;
stayStill = false;
}
else
{
stayStill = true;
anim.SetBool("isWalking", false);
}
if (moveRight && ! moveLeft && ! stayStill)
{
rb.velocity = new Vector2(1 * moveSpeed, 0);
anim.SetBool("isWalking", true);
sP.flipX = true;
}
if (! moveRight && moveLeft && ! stayStill)
{
rb.velocity = new Vector2(-1 * moveSpeed, 0);
anim.SetBool("isWalking", true);
sP.flipX = false;
}
}
}
Any ideas?
Answer by N-8-D-e-v · Jun 08, 2020 at 06:04 PM
Well first off, you don't need to make two vector 2s for right and left, just use Vector2.right and -Vector2.right. Also, what your code is doing is checking if the random number is 2, then checking if it's three and if it's not it stays still, regardless of if the number was 2. So first change your code
if (randomNum == 2)
{
moveRight = true;
moveLeft = false;
stayStill = false;
}
else if //make sure there's an else if
(randomNum == 3)
{
moveRight = false;
moveLeft = true;
stayStill = false;
}
else
{
stayStill = true;
anim.SetBool("isWalking", false);
}
Next, try putting a physics material on the ground that has 0 friction. Then, another case where "else if" would be better, change your code
if (moveRight && ! stayStill)
{
rb.velocity = new Vector2(moveSpeed, 0); //you don't need the * 1, as that just returns the same number
anim.SetBool("isWalking", true);
sP.flipX = true;
}
else if (moveLeft && ! stayStill) //add an else
{
rb.velocity = new Vector2(-1 * moveSpeed, 0);
anim.SetBool("isWalking", true);
sP.flipX = false;
}
You should do this, as you can't have both options, if you have one you can't do the other. You can't be moving left and right at the same time
Hope this helps