Home > Software engineering >  How I can move player left or right with infinite runner game here. using character controller
How I can move player left or right with infinite runner game here. using character controller

Time:12-02

public class PlayerMove : MonoBehaviour
{
    public float speed;
    private float yVelocity;
    public CharacterController player;
    public float jumpHeight =10.0f;
    public float gravity = 1.0f;
    //public float gravityScale = 1;

    private void Start()
    {
        player = GetComponent<CharacterController>();
    }

    void Update()
    {
        Vector3 direction= new Vector3(0, 0, 1);
        Vector3 velocity= direction * speed;

        if (player.isGrounded == true)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                yVelocity = jumpHeight;
            }
        }
        else
        {
            yVelocity -= gravity;
        }
        velocity.y = yVelocity;
    
        player.Move(velocity * Time.deltaTime);
    }
}

I tried Rigidbody & much more script but my player doesn't jump if my player jump then my doesn't move left or right sometimes my player stocked in ground.. tell me the right way of script where I can use

CodePudding user response:

For the left/right movements you can try this simple code :

using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    public float speed;
    private float yVelocity;
    public CharacterController player;
    public float jumpForce = 10.0f;
    public float moveForce = 5.0f;
    public float gravity = 1.0f;

    private void Start()
    {
        player = GetComponent<CharacterController>();
    }

    void Update()
    {
        Vector3 direction = new Vector3(0, 0, 1);
        Vector3 velocity = direction * speed;

        // Add left/right movement
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            velocity  = Vector3.left * moveForce;
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            velocity  = Vector3.right * moveForce;
        }

        if (player.isGrounded)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                yVelocity = jumpForce;
            }
        }
        else
        {
            yVelocity -= gravity;
        }

        velocity.y = yVelocity;
        player.Move(velocity * Time.deltaTime);
    }
}

You can also look at this post Components applied on player GameObject

  • Related