Skip to content

Instantly share code, notes, and snippets.

@nicloay
Last active August 29, 2015 13:57
Show Gist options
  • Save nicloay/9615911 to your computer and use it in GitHub Desktop.
Save nicloay/9615911 to your computer and use it in GitHub Desktop.
Unity3d horizontal mobile platform controller. no lag with physics. don't use it.. see https://gist.github.com/nicloay/9662874
public class HorizontalMovePlatformController : MonoBehaviour {
public float routeLenght = 10;
public float horizontalSpeed = 10;
[Range (0,1)]
public float startRelativePosition=0;
public bool goRight;
Vector3 basePosition, remotePosition;
void Start(){
basePosition = transform.position;
remotePosition = getRemotePosition();
transform.position = Vector3.Lerp(basePosition, remotePosition, startRelativePosition);
updateVelocity();
}
Vector2 velocity;
void Update(){
if (goRight && (transform.position.x - remotePosition.x) > 0){
goRight = false;
updateVelocity();
} else if (!goRight && (transform.position.x - basePosition.x) <0){
goRight = true;
updateVelocity();
}
rigidbody2D.velocity = velocity;
}
void updateVelocity(){
velocity = new Vector2( goRight ? horizontalSpeed : -horizontalSpeed, 0);
}
Vector3 getRemotePosition(){
return basePosition + new Vector3(routeLenght, 0, 0);
}
Vector3 remoteVelocity;
void OnCollisionStay2D(Collision2D collision){
remoteVelocity= collision.rigidbody.velocity;
remoteVelocity.x = rigidbody2D.velocity.x;
}
void OnDrawGizmos(){
if (Application.isPlaying){
Gizmos.DrawLine(basePosition, remotePosition);
} else {
Vector2 boxSize = (collider2D as BoxCollider2D).size;
basePosition = transform.position;
remotePosition = getRemotePosition();
Gizmos.DrawLine(transform.position, remotePosition);
Gizmos.DrawCube(Vector3.Lerp(basePosition, remotePosition, startRelativePosition),boxSize);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment