- Home /
Basic AI Movement C#
Hello there. I am currently working on a project for my beginning programming class and have a problem. My enemy is supposed to go left and right on the screen and go back and forth while dropping objects toward the player. In my code the enemy goes left and then stops at the edge of the screen but wont go in the other direction. Any help would be appreciated. I am using C#. Thank you for your time.
Code:
using UnityEngine;
using System.Collections;
public class ThiefMove : MonoBehaviour
{
public int moveSpeed = 140; //per second
Vector3 computerDirection = Vector3.left;
Vector3 moveDirection = Vector3.zero;
Vector3 newPosition = Vector3.zero;
void Start ()
{
}
void Update ()
{
Vector3 newPosition = new Vector3(-1,0,0) * (moveSpeed * Time.deltaTime);
newPosition = transform.position + newPosition;
newPosition.x = Mathf.Clamp(newPosition.x, -101, 126);
transform.position = newPosition;
if(newPosition.x > 126)
{
newPosition.x = 126;
computerDirection.x *= -1;
}
else if(newPosition.x < -101)
{
newPosition.x = -101;
computerDirection.x *= -1;
}
}
}
Answer by raoz · Apr 04, 2012 at 05:01 AM
Vector3 newPosition = new Vector3(-1,0,0) * (moveSpeed * Time.deltaTime)
should be
Vector3 newPosition = computerDirection * (moveSpeed * Time.deltaTime)
Answer by by0log1c · Apr 04, 2012 at 05:20 AM
Like raoz mentions, you'll need to use the computerDirection variables for it to work, but even then, there's a subtle error, I believe.
You clamp the x position between -101 and 126 and right after you are looking for 126. I believe it will never return true, you should use = .
Answer by Nutcrackerz06 · Apr 04, 2012 at 10:16 PM
Thank you guys so much for your help. It worked. I appreciate your help. You really helped me out.
This isn't an answer to the question. Use the Comments section, it's not as if it isn't there.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Adding Wander option to AI 1 Answer
Multiple Cars not working 1 Answer
Simple AI In 2D - C# 1 Answer
Random movement AI 0 Answers