I know this is a very simple question for some people, but there are a few complications.
The player is moving based on camera direction (where the camera is pointing to)
The player floats slightly above the ground (I don’t know if this is a complication but it is something I want to know how to fix)
The camera follows the player
This the code for the player movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
private Rigidbody rb;
public int baseSpeed;
public int sprint;
private int currentSpeed;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void Update ()
{
//this makes the player go where the camera is pointing
transform.position = transform.position + Camera.main.transform.forward*currentSpeed*Time.deltaTime;
//this makes the player sprint when the shift key is pressed
if (Input.GetKey(KeyCode.LeftShift))
{
currentSpeed = baseSpeed + sprint;
}
else
{
currentSpeed = baseSpeed;
}
}
}
This is the code for the camera:
using UnityEngine;
using System.Collections;
public class Orbit : MonoBehaviour {
public float turnSpeed = 4.0f;
public Transform player;
public float height = 1f;
public float distance = 2f;
private Vector3 offsetX;
void Start () {
offsetX = new Vector3(0, height, distance);
}
void LateUpdate()
{
offsetX = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offsetX;
transform.position = player.position + offsetX;
transform.LookAt(player.position);
}
}
Please also help me fix errors in the code as well. Your help is greatly apprecieted.
// New Variable
public float jumpForce;
// Inside Update
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector3 (rb.velocity.x,jumpForce,rb.velocity.z);
}
Thank you very much, this worked. But when I press space while my player is in the air, the player jumps again in the air. How do I fix this? I saw a forum on how someone made a function called “isGrounded”. But when I tried this it didn’t seem to work. Also when I am making the player sprint (by pressing shift), the “jump” does not work.
Try to use a raycast. You can put it in a function so you don’t have to call it all the time, just when needed, but I’m lazy today:
// New Variables
RaycastHit hit;
float distanceToGround = 0.5f;
bool isGrounded = false;
// Put this inside Update
if (Physics.Raycast(transform.position, Vector3.down, out hit, distanceToGround, 1 >> 8))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
I have no idea why it doesn’t jump when you sprint, if it does it normally it should do it sprinting too. Either way, there are literally hundreds of tutorials in Youtube on how to make simple platformers, which are probably gonna help you way more than me.
Thank you very much. This worked perfectly. Also when I am making the player sprint (by pressing shift), the “jump” does work like normal. Thank you very much.