I'm setting up a basic mario-like 2D platformer and I'm trying to give 'enemies' a patrolling path on a platform. (just like the turtles in Super Mario Bros). All they do is patrol from left to right and back. <--->
Currently my game object is walking to left and right in the middle of my scene. Despite me positioning my game object as far left as I can, at first it walks to the center of the scene and continues acting out his patrol in the center of my scene.
What I can't seem to figure out is adjusting the position where he patrols. I don't want him to patrol in the center of the scene.
I think I should use the originalX
position in the Update
function but I'm not sure how (I could be wrong)?
This is the script that is linked to my enemy gameobject.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public float walkSpeed = 1.0f; // Walkspeed
public float wallLeft = 0.0f; // Define wallLeft
public float wallRight = 5.0f; // Define wallRight
float walkingDirection = 1.0f;
Vector2 walkAmount;
float originalX; // Original float value
void Start () {
this.originalX = this.transform.position.x;
}
// Update is called once per frame
void Update () {
walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
walkingDirection = -1.0f;
} else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
walkingDirection = 1.0f;
}
transform.Translate(walkAmount);
}
}