- Home /
moving object on x axis without affecting z axis
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.
Answer by aldonaletto · Nov 01, 2013 at 01:12 AM
Space.Self in Translate makes the object move in its local directions - if the object has any rotation, it will move in other axes too. Try Space.World instead: this will Translate only in the X axis with this code. By the way, you could improve performance and write a lot less if the script reference was cached in a variable at Start:
#pragma strict
var range : float;
private var start_x : float;
private var attribs: NPC_set_attributes; // reference to the NPC_set_attributes script
function Start () {
start_x = transform.position.x;
attribs = GetComponent(NPC_set_attributes); // get the script
range = attribs.npc_patrolling_range;
}
function Update () {
transform.Translate(Vector3(attibs.npc_move_speed*Time.deltaTime, 0.0, 0.0), Space.World);
if(transform.position.x >= start_x + range){
Change_direction();
} else if(transform.position.x <= start_x-range) {
Change_direction();
}
}
function Change_direction () {
attribs.npc_move_speed = -attribs.npc_move_speed;
attribs.npc_facing_left = !attribs.npc_facing_left;
}
Your answer
Follow this Question
Related Questions
if(transform.Rotate) Doesn't Work? 4 Answers
[Javascript] Check X and Z coordinates for an instance of a certain object 0 Answers
Only one animation playing NON-STOP!!? 2 Answers
How do I create a tool similiar to the object movement gizmo in unity 2 Answers
How do I get the edge of an object from transform.position? 2 Answers