What am I missing here? Unity isn’t giving me any scripting errors. But I cant get off the ground
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActorMovement : MonoBehaviour {
public float speed = 10;
public float jumpForce = 10f;
public bool isGrounded;
public Vector3 jump;
CharacterController controller;
Rigidbody rb;
void Start () {
controller = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 3.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
void Update () {
float hAxis = Input.GetAxis("Horizontal");
float vAxis = Input.GetAxis("Vertical");
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
controller.SimpleMove(transform.forward * vAxis * speed * Time.deltaTime);
transform.Rotate(transform.up, hAxis + Time.deltaTime);
}
}
Lets do some debugging!
Why dont you add a debug log to see what is going on. For example:
Debug.Log("Space: " + Input.GetKeyDown(KeyCode.Space) + ", isGrounded: " + isGrounded);
Compare that to what you think the values should be.
isGrounded is a public variable. What is it’s value when you’re playing?
You guys are quick,
With the public var enabled it goes from:
Space: False, isGrounded: True
to:
Space: False, isGrounded: False
With it Disabled:
Space: False, isGrounded: False
to:
Space: False, isGrounded: False
Weird that “space” is “false” in all cases.
Try using
Input.GetKey(KeyCode.Space);
instead of GetKeyDown.
Solved in the end by my teacher directing me to unity documentation examples
[RequireComponent(typeof(CharacterController))]
public class ActorMovement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
// Debug.Log("Jump: " + Input.GetButton("Jump") + " ,isGrounded: " + controller.isGrounded);
float rotation = Input.GetAxis("Horizontal");
transform.Rotate(transform.up, rotation);
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Thanks so much for posting your answer!