I have an object which I want to move left and right and I am using the following code to do so
xPos= Mathf.Sin(Time.time);
transform.position = new Vector3(xPos, 0, 0);
This puts the object in the center of the world and it does move it left and right but I want it to stay in its current position and then move. If the transform.position.x is at 10, how can I move it so it goes to 11 and then to 9? I have tried
xPos += transform.position.x;
to get the current position but then the behavior completely changes.
Your object goes to the centre of the world because you set its position based on Sin [ a range of -1 to 1]. All you need to do is save an offset. Take a look at the code below.
The reason “the behaviour completely changes” when using += is because you are adding anywhere between -1 and 1 unites every frame (60 time per second). This will make your object shoot across the screen. You can use Delta Time as a scaler to control it’s speed (it’s also a good rule of thumb to use delta time on all movement code).
You can control the speed of oscillation by introducing a “time” variable that controls the time period i.e. the time taken to complete left and right motion:
This is more flexible than using a “speed” variable
Plus, the code makes sure that the object always starts at the initial position. The reason timeSinceStart is used is to offset the time value so that the very first frame the Mathf.Sin() function evaluates to ‘-1’, and the object starts at the initial position, instead of halfway between the beginning and the destination.
Feel free to ask me doubts or inform me about bugs