Issue with basic enemy AI script.
Code:
using UnityEngine;
using System.Collections;
public class enemyAI : MonoBehaviour
{
private Rigidbody2D myRigidbody;
private bool moveRight;
private Vector2 moveLocation;
[SerializeField]
private float speed;
[SerializeField]
private Vector2 tra1;
[SerializeField]
private Vector2 tra2;
// Use this for initialization
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
moveRight = true;
}
// Update is called once per frame
void FixedUpdate () {
Debug.Log(moveRight);
tra1 = transform.position;
EmemyMovement();
tra2 = transform.position;
if (tra1.x == tra2.x)
{
moveRight = !moveRight;
}
}
private void EmemyMovement()
{
if (moveRight == true)
{
moveLocation = new Vector2(transform.position.x + speed, transform.position.y);
myRigidbody.MovePosition(moveLocation);
}
else
{
moveLocation = new Vector2(transform.position.x + -speed, transform.position.y);
myRigidbody.MovePosition(moveLocation);
}
}
}
It should be that it moves right until it stops then it moves left but when I run it the variable moveRight changes between true and false every frame and bounces forwards and backwards. Any help?
"...moves right until it stops..." could you be more specific than that? You are setting tra1 and tra2 to the same position and then asking if they are the same. This is always going to be the same so the bool moveRight will always be flipped.
tra1 = transform.position;
Ememy$$anonymous$$ovement();
tra2 = transform.position;
if (tra1.x == tra2.x)
{
moveRight = !moveRight;
}
@Pengocat I mean it would move right until it hit a wall and couldn't move anymore. What is supposed to happen is that tra1 is checked, the enemy moves right then tra2 is checked. If the moving was successful the bool isn't flipped and if the rigidbody movement didn't go anywhere the bool is flipped.
Sorry if I was unclear.
Perhaps you can use something like this in some way. It goes towards the current waypoint then when close it picks the other waypoint. It is a big rough but it works.
public float speed = 250f;
public Transform waypointPositionA;
public Transform waypointPositionB;
Rigidbody2D myRigidbody;
Vector3 direction;
enum Waypoint
{
A,
B
}
Waypoint currentWaypoint = Waypoint.A;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Ememy$$anonymous$$ovement();
}
void Ememy$$anonymous$$ovement()
{
// If close to A switch direction towards waypoint B
if (Vector2.Distance(transform.position, waypointPositionA.position) < 0.1f && currentWaypoint != Waypoint.B)
{
currentWaypoint = Waypoint.B;
// Instantly stop the rigidbody to change direction rapidly
myRigidbody.velocity = Vector2.zero;
}
// If close to B switch direction towards waypoint A
else if (Vector2.Distance(transform.position, waypointPositionB.position) < 0.1f && currentWaypoint != Waypoint.A)
{
currentWaypoint = Waypoint.A;
myRigidbody.velocity = Vector2.zero;
}
// Calculate the vector towards current set waypoint
switch (currentWaypoint)
{
case Waypoint.A:
direction = (waypointPositionA.position - transform.position).normalized;
break;
case Waypoint.B:
direction = (waypointPositionB.position - transform.position).normalized;
break;
}
// $$anonymous$$ove the rigidbody towards the waypoint
myRigidbody.AddForce(direction * speed * Time.fixedDeltaTime);
}
Answer by ericbegue · Dec 18, 2016 at 06:18 PM
You want the AI to move back and forth between two walls? Here is a simplication of your script, with some comments:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
// Note: public variables are serialize by default.
public float speed = 1.0f;
public Vector2 leftWall;
public Vector2 rightWall;
Vector3 direction;
// Use this for initialization
void Start()
{
direction = Vector3.right;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 velocity = speed*direction;
// Don't forget Time.Delta time to make the movement frame-rate independent.
transform.position += velocity * Time.deltaTime;
if (transform.position.x > rightWall.x)
{
transform.position = rightWall;
direction = Vector3.left;
}
if (transform.position.x < leftWall.x)
{
transform.position = leftWall;
direction = Vector3.right;
}
}
}
If you want to make more advanced AI, I would suggest to have a look at Behaviour Tree. It's an AI technique that simplifies the development of complex (or simple) AI. I've made a scripting framework based on Behaviour Tree ( see Panda BT: www.pandabehaviour.com ).
Developing AIs using this tool consist of defining "tasks" and use them from a BT script. For instance, to make an AI that move to arbitrary locations, you first need to make a "task" to handle the AI movement. This is implemented as a function on a MonoBehaviour:
using UnityEngine;
using Panda; // We are using Panda BT
public class EnemyAIBT : MonoBehaviour
{
public float speed = 1.0f;
public Transform[] locations; // Array of locations.
Vector3 destination;
[Task] // <-- This marks a function as a task.
void MoveTo(int locationIndex)
{
// Set the destiantion when the task is starting.
if (Task.current.isStarting)
destination = locations[locationIndex].position;
// Move towards the destination on each tick (Update).
transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
// The task is done when we have reached the destination.
if (transform.position == destination)
Task.current.Succeed();
}
}
Once, you've defined some tasks, you can use them as building blocks from a BT script to define how your AI behaves. For instance, to make an AI that move back and forth between the first 2 locations, its BT script would be:
tree("Root")
sequence
MoveTo(0)
MoveTo(1)
This is an extremely simple BT, but you can do much more with Behaviour Tree. The package contains several examples from simple to advanced.
If you have any question about using this tool you are welcome on this forum thread.
Your answer
Follow this Question
Related Questions
SetDirty won't work on Nested List 1 Answer
unity3d 5 game on fullscreen shows only half of game screen 4 Answers
Enemy watches player and shoots but bullets will not project 0 Answers
How do I make an AI(cube) that follows and rams the player? 0 Answers
A little doubt about creating a Talking BOT that simulates AI, for iOS system using Unity. 0 Answers