Switching lanes
Hi guys, i'm trying to make an endless runner,3 lanes type game.The character switches lanes,but 1 lane isn't enough, want him to switch the distance of 2 lanes at 1 button press. Another thing, how can i make him switch lanes smooth,rather than snapping to lane ? Thank you in advance !
void Start () {
lane = 0;
controller = GetComponent<CharacterController> ();
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (Time.time < animationDuration)
{
controller.Move (Vector3.forward * speed * Time.deltaTime);
return;
}
moveVector = Vector3.zero;
if (controller.isGrounded) {
verticalVelocity = -0.5f;
} else
{
verticalVelocity -= gravity * Time.deltaTime;
}
if (Input.GetButtonDown("Jump"))
{
anim.SetTrigger("isJumping");
verticalVelocity = 4.0f;
}
if (Input.GetButtonDown ("Fire1"))
{
anim.SetTrigger ("isRolling");
}
//x - left right
moveVector.x = Input.GetAxisRaw("Horizontal") * speed;
//y - up down
moveVector.y = verticalVelocity;
//z - forward backward
moveVector.z = speed;
controller.Move (moveVector * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if (lane > -1)
lane--;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
if (lane < 1)
lane++;
}
Vector3 newPosition = transform.position;
newPosition.x = lane;
transform.position = newPosition;
transform.Rotate (Vector3.up, 0.0f);
}
Answer by UnityCoach · Mar 25, 2017 at 02:32 PM
Hi, I would break this down into 2 components (one for input, one for control).
In the controller, you can have properties (variable and accessor) like :
float delta = 0f;
float speed = 0.1f; // units per second
private int _lane;
public int lane
{
get { return _lane ; }
set
{
if (_lane != value) // the property is likely to be assigned every frame if it's done in Update, although the value will not change every time
{
float originX = _lane;
_lane = Mathf.Clamp (value, -1, 1); // clamping the value so that you can't go beyond limits
delta = _lane - originX;
}
}
}
void Update ()
{
if (delta == 0)
return;
transform.Translate (delta * speed * Time.deltaTime, 0, 0); // using transform translate to move when the value changed
if (Mathf.Approximately (transform.position.x, lane)
{
delta = 0;
transform.position = new Vector3 (lane, transform.position.y, transform.position.z);
}
}
Follow this Question
Related Questions
Animations get screwed up when I add OnAnimatorMove function 0 Answers
How can I get the player to face the direction it is going in a Unity 2D Game? 0 Answers
How to apply Character Movement Controls to a skeletal rig? 0 Answers
Input.GetAxisRaw always returns -0.6 1 Answer
SetBool animation state based on direction object is moving 0 Answers