Hello! This is my first post on this forum since i tend to want to try and fix things my own way. This time it’s really not working out as i intended. Im still very new to Unity so all advice is appreciated. If anyone got time help would be much appreciated.
During the last couple of days i’ve been wanting to implement a simple object that wanders (AI), all tutorials i’ve found has been using transforms and positions which id prefer not to use since i really like to work with the physics. Today i’ve been reiterating the same code so mant times that i cannot tell right from wrong anymore…
My goal is to set a vector & direction in order to get my object to move by giving it a random vector2 for direction and then apply the movespeed according to the movement. Im trying to use bools to see if the object can move or if it can go into Idle. On paper i feel that im doing it correctly but obviously not…
My problem right now is that the object never moves, or atleast it did one time.
Down below is my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NpcWander : MonoBehaviour
{
public Rigidbody2D RB;
private Vector2 movement;
public float moveSpeed;
public Vector2 direction;
bool canMove = true;
bool canIdle = false;
public float startWaitTime = 5f;
private float waitTime;
void Start(){
direction = new Vector2(Random.Range(-1,1),Random.Range(-1,1));
waitTime = startWaitTime;
}
void update(){
SetDirection();
if(canMove){
//move as long as canMove is true, after the object has moved the bool is set to false in order to go into Idlemode.
RB.velocity = new Vector2(movement.x * moveSpeed, movement.y * moveSpeed);
canMove = false;
}else {
canIdle = true;
}
if(canIdle){
//Go into Idle until time is up
if(waitTime > 0){
waitTime -= Time.deltaTime;
}
if (waitTime <=0){
canMove = true;
canIdle = false;
}
}
}
void SetDirection(){
movement = new Vector2(direction.x, direction.y).normalized;
}
}