- Home /
Moving box
I'm working on a game where the player has to pass through a room where some rocks move back and forth, opening and closing the way. I can get the rocks to move using a script with a timer, when it reachs a certain number the rocks changes direction. Is there anyway I can write a script like, "if the rock gets to a certain position it changes direction"? It needs to b done using C#.
Answer by syclamoth · Oct 03, 2011 at 01:28 AM
You could do something like-
public Vector3 targetPos1;
public Vector3 targetPos2;
public float moveTime;
float curMoveProportion = 0;
Vector3 targetPos = Vector3.zero;
Vector3 prevPos = Vector3.zero;
// in Start, set up whichever is the first position to be going to
void Start()
{
targetPos = targetPos2;
transform.position = targetPos1;
prevPos = transform.position;
}
// in Update, move the box around between the two points
void Update()
{
curMoveProportion += (Time.deltaTime / moveTime);
if(curMoveProportion >= 1)
{
if(targetPos == targetPos1)
{
targetPos = targetPos2;
} else {
targetPos = targetPos1;
}
prevPos = transform.position;
curMoveProportion = 0;
}
transform.position = Vector3.Lerp(prevPos, targetPos, curMoveProportion);
}
Solved, found a way to discover the position, thanks alot syclamoth
If you're using transforms, you can get the position using transform.position.
Answer by caiodmk · Oct 03, 2011 at 03:30 AM
I'm very new to unity and C#, I tried to understand the code. The problem I'm having now is i don't know how to set targetPos1 and targerPos2 as a certain position. I tried to convert them into Transform instead of Vector3(so i can create an Empty Object and place it where i want), but this provides an error. How do i set up where my 2 key posisions will be?
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Attaching new script vs. MonoBehaviour inheritance 1 Answer
Script Editors for Unity 3 Answers
movement 2d in a grid 3 Answers