- Home /
Resetting a position after reaching a certain point
I'm currently working on a game that has moving cars moving through my stage. I want to be able to return to their original positions once they reach a certain point, but the code I'm using doesn't seem to work. Relatively new to C#, any help would be appreciated.
using UnityEngine;
using System.Collections;
public class CarmovingX : MonoBehaviour {
public int maxXPosition = 50;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(Vector3.up * Time.deltaTime);
if( gameObject.transform.position.x >= maxXPosition)
{
transform.Translate(Vector3(12,y,z));
}
}
}
Thanks
Answer by Heisenbug · Nov 05, 2012 at 01:24 PM
I suggest you to store original position and orientation of your GameObject. When you decide to restore them, simply assign the stored value to its Transform. An example:
public class CarmovingX : MonoBehaviour {
public int maxXPosition = 50;
private Vector3 initialPos;
private Quaternion initialRotation;
// Use this for initialization
void Start () {
initialPos = transform.position;
initialRotation = transform.rotation;
}
// Update is called once per frame
void Update () {
transform.Translate(Vector3.up * Time.deltaTime);
if( gameObject.transform.position.x >= maxXPosition)
{
transform.rotation = initialRotation;
transform.position = initialPosition;
}
}
}
If your CarmovingX GameObject is child of another GameObject, you may consider using Transform.localPosition and Transform.localRotation instead.
transform.position = initialPosition it wrong declaration transform.position = initialPos it right declaration please update this if nt user may confuse .......
For some reason my gameObject became very jittery. However, the example worked perfectly once I removed the following line.
transform.Translate(Vector3.up * Time.deltaTime);
Answer by JBaBe · Aug 04, 2016 at 12:54 PM
I used this script for my own project, i just had to replace the X axis by a Y axis to fit my needs. works well but i would like to only reset to initial position on the Y and Z axis how can I stop the script form reseting the gameobject's position along the X axis ?
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How can I reset the y position of a gameobject to a certain value each frame? 1 Answer
Multiple Cars not working 1 Answer
Multiple resolutions considerations for Sprite Manger 2 0 Answers
Mathf.Lerp not working 2 Answers