I have an NPC object in my 2d sidescrolling game.
While he is far away from the player, I want him to patrol nearby area, by changing it’s x coordinate in a range, but while x coordinate is changing, z coordinate is changing too. Here is the code:
#pragma strict
var range : float;
private var start_x : float;
function Start () {
start_x = transform.position.x;
range = gameObject.GetComponent(NPC_set_attributes).npc_patrolling_range;
}
function Update () {
transform.Translate(Vector3(gameObject.GetComponent(NPC_set_attributes).npc_move_speed*Time.deltaTime, 0.0, 0.0), Space.Self);
if(transform.position.x >= start_x + range){
Change_direction();
} else if(transform.position.x <= start_x-range) {
Change_direction();
}
}
function Change_direction () {
gameObject.GetComponent(NPC_set_attributes).npc_move_speed = -gameObject.GetComponent(NPC_set_attributes).npc_move_speed;
gameObject.GetComponent(NPC_set_attributes).npc_facing_left = !gameObject.GetComponent(NPC_set_attributes).npc_facing_left;
}
Don’t know what to do. “Freeze Position Z” won’t help, because I need to be able to move my object on z axis too.