hi guys,
am trying to make my character moves lanes smoothly with out him teleporting i tried to element what i read on this post Rigidbody smooth lane transition - Questions & Answers - Unity Discussions, however i wast success full as it doesn’t move using the arrow keys however when i press the jump button it moves to the right hand side, any help or guide would be great
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
private bool gameStarted; // try and access this from the start script so when the player presses start the animation can start to run
private float lane;
private float runSpeed = 0.1f;
private float jumpForce = 6;
private bool OnGround;
private bool isDead;
Rigidbody myBody;
Animator myAnim;
private void Start()
{
lane = 0;
myBody = GetComponent<Rigidbody>();
myAnim = GetComponent<Animator>();
OnGround = true;
isDead = false;
}
private void Update()
{
// Lanes Movement
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
if(lane > -1)
{
lane -= 3.5f;
}
}
if(Input.GetKeyDown(KeyCode.RightArrow))
{
if(lane < 1)
{
lane += 3.5f;
}
}
Vector3 newPosition = myBody.position;
newPosition.x = Mathf.MoveTowards(newPosition.x, lane, Time.deltaTime);
myBody.position = newPosition;
// Move Speed
if(isDead == true)
{
myBody.AddForce(new Vector3(0, 0, 0));
}
else
{
myBody.MovePosition(transform.position + transform.forward * runSpeed);
}
// Jump Function
if(OnGround)
{
if(Input.GetButtonDown("Jump"))
{
myAnim.SetBool("Jumping", true);
Invoke("StopJumping",0.1f);
myBody.velocity = new Vector3(jumpForce / 3, jumpForce, 0);
OnGround = false;
}
}
// sliding function
if(Input.GetKeyDown(KeyCode.DownArrow) && OnGround == true)
{
myAnim.SetBool("Sliding", true);
Invoke("StopSliding", 0.1f);
}
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ground"))
{
OnGround = true;
}
else if (other.gameObject.CompareTag("Death"))
{
isDead = true;
myAnim.SetBool("Death", true);
Invoke("StopDeath",0.1f);
}
}
private void StopJumping()
{
myAnim.SetBool("Jumping", false);
}
private void StopSliding()
{
myAnim.SetBool("Sliding", false);
}
private void StopDeath()
{
myAnim.SetBool("Death", false);
}
}