Smoothly switch between 2 lanes.

Updated on November 13, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on November 13, 2017

This is my code to switch my player (who is a cube for the time being) between 2 lanes. However it creates a teleport kind of effect. Can someone help me out in smoothing the motion. I am a beginner so it would be kind if you could explain it a bit.

Code-

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
public float movedist=150;
public float moveforce=300;
private int playerpos = 1;
private Rigidbody rb;
public float switchspeed=300f;

void Start()
{
rb = GetComponent<Rigidbody> ();

}
void FixedUpdate()
{
rb.AddForce (moveforce * Time.deltaTime, 0, 0);
}
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
if (playerpos < 2) {
Vector3 pos = transform.position;
Vector3 switch1 = new Vector3 (transform.position.x, transform.position.y, movedist);
transform.position = Vector3.Lerp (pos, switch1, switchspeed);
playerpos++;
} else if (playerpos > 0) {
Vector3 pos = transform.position;
Vector3 switch2 = new Vector3 (transform.position.x, transform.position.y, 0);
transform.position = Vector3.Lerp (pos, switch2, switchspeed);
playerpos–;
}
}
}
}

Thanks.

  • Liked by
Reply