You have the right idea, but the While Loop is going to hold up your thread and nothing else will happen.
What I’m doing here is having a constant rate of speed, and just flip it when it gets to either side. By flip it, I mean just multiplying the speed by-1, which will cause it to move in the opposite direction. Also, I recommend using variables for the min/max sides. And another way of doing this is using two empty GameObjects for the min and max.
But there ya go! I hope this answers your question If it does, please mark it as the answer. Thanks!
Also, I’m assuming you’re attaching this script directly onto the platform.
using UnityEngine;
using System.Collections;
public class PlatformController : MonoBehaviour{
public float speed = 5;
void Update(){
if(transform.position.x >= 20){
speed *= -1;
}
if(transform.position.x <= -20){
speed *= -1;
}
transform.Translate (Vector3.right * speed * Time.deltaTime);
}
}
Using float variables for the min/max
using UnityEngine;
using System.Collections;
public class PlatformController : MonoBehaviour{
public float speed = 5;
public float maxLeft = -8;
public float maxRight = 8;
void Update(){
if(transform.position.x >= maxRight){
speed *= -1;
}
if(transform.position.x <= maxLeft){
speed *= -1;
}
transform.Translate (Vector3.right * speed * Time.deltaTime);
}
}
This is using two empty GameObjects to help visually set the min/max. I personally prefer this way, because it’s easy to see exactly where the platform will be, rather than guessing with float numbers.
using UnityEngine;
using System.Collections;
public class PlatformController : MonoBehaviour{
public float speed = 5;
public Transform maxLeft;
public Transform maxRight;
void Update(){
if(transform.position.x >= maxRight.position.x){
speed *= -1;
}
if(transform.position.x <= maxLeft.position.x){
speed *= -1;
}
transform.Translate (Vector3.right * speed * Time.deltaTime);
}
}