I have a spotlight that moves around randomly. It needs to not exit the map, I created a script to make sure it doesn’t leave some coordinates. If it does it moves it appropriately in the direction away from where it is.
var Mother : GameObject;
function Update (){
if(Mother.position.x >= 116){
Mother.transform.position += (Vector3(-1,0,0));
}
if(Mother.position.x <= -80){
Mother.transform.position += (Vector3(1,0,0));
}
if(Mother.position.y >= 110){
Mother.transform.position += (Vector3(0,-1,0));
}
if(Mother.position.y <= -65){
Mother.transform.position += (Vector3(0,1,0));
}
}
Is does not work. I am very upset.
If you know how to do this please give me someway to do this. whether its a script you made or a place that teaches you how to do this, the projects due next week. thank you so much for your help.
Ok, Lets say you want to keep the X value of a Vector3 between a maximum and a minimum value
You can simply go this:
//The variables we will use
var vector:Vector3;
var maximum:float;
var minimum:float;
//Now to clamp the x value between maximum and minimum
//so:
vector.x = Mathf.Clamp(vector.x, minimum, maximum);
//This will keep vector.x between the value of minimum and maximum
//You can do this for all other components of the vector too
vector.y = Mathf.Clamp(vector.y, minimum, maximum);
//etc...
The problem with your code in the comments are:
- why are you clamping Time? WTF??
- Your trying to clamp the position variable of a GameObject, but a GameObject has no position, it has a transform component with a position
Instead you should do this:
function Update() {
Mother.transform.position.x = Mathf.Clamp(Mother.transform.position.x, minimum, maximum)
}
Hope this helps, Benproductions1