x


Check if an object is changing position C#

Hello, how do I check if an object is changing position or not. I wan't to know this because I want to be able to do something, when an objects x position is getting greater, and I want to do something else when it's getting smaller.

more ▼

asked Dec 17 '11 at 04:19 PM

Kenneth Andersen gravatar image

Kenneth Andersen
27 8 8 10

(comments are locked)
10|3000 characters needed characters left

1 answer: sort oldest

To monitor only the X coordinate of the object's position, you could do this:

Vector3 lastPos;
Transform obj; // drag the object to monitor here
float threshold = 0.0f; // minimum displacement to recognize a 

void Start(){
  lastPos = obj.position;
}

void Update(){
  Vector3 offset = obj.position - lastPos;
  if (offset.x > threshold){
    lastPos = obj.position; // update lastPos
    // code to execute when X is getting bigger
  }
  else
  if (offset.x < -threshold){
    lastPos = obj.position; // update lastPos
    // code to execute when X is getting smaller 
  }
}

This will execute the code once when the X distance from the lastPos exceeds threshold. This also updates lastPos when the code is executed, thus the distance from this point must again exceed threshold for the code to be executed again.
This script is intended to be attached to another object; if you plan to use it in the monitored object, replace obj. in the text by transform. (or assign obj = transform; at Start).

more ▼

answered Dec 17 '11 at 05:25 PM

aldonaletto gravatar image

aldonaletto
41.5k 16 42 197

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4169
x1095
x886

asked: Dec 17 '11 at 04:19 PM

Seen: 1140 times

Last Updated: Dec 17 '11 at 05:25 PM