Algorithm to shift the car
Posted
by
Simran kaur
on Game Development
See other posts from Game Development
or by Simran kaur
Published on 2014-08-23T12:46:57Z
Indexed on
2014/08/23
16:34 UTC
Read the original article
Hit count: 331
I have a track that can be divided into n number of tracks and a car as GamObject. The track has transforms such that some part of the track's width lies in negative x axis and other in positive.
Requirement: One move should cross one track. On every move(left or right), I want the car to reach exact centre of the next track on either sides i.e left or right. My code:
Problem: : Because of negative values , somewhere I am missing out something that is making car move not in desirable positions and that's because of negative values only.
variable tracks
is the number of tracks the whole track is divided in.
variable dist
is the total width of the complete track.
On left movement:
if (Input.GetKeyDown (KeyCode.LeftArrow))
{
if (this.transform.position.x < r.renderer.bounds.min.x + box.size.x)
{
this.transform.position = new Vector3 (r.renderer.bounds.min.x + Mathf.FloorToInt(box.size.x), this.transform.position.y, this.transform.position.z);
}
else
{
int tracknumber = Mathf.RoundToInt(dist - transform.position.x)/tracks;
float averagedistance = (tracknumber*(dist/tracks) + (tracknumber-1)*(dist/tracks))/2;
if(transform.position.x > averagedistoftracks)
{
amountofmovement = amountofmovement + (transform.position.x - averagedistance);
}
else
{
amountofmovement = amountofmovement - (averagedistance - transform.position.x);
}
this.transform.position = new Vector3 (this.transform.position.x - amountofmovement, this.transform.position.y, this.transform.position.z);
}
}
© Game Development or respective owner