Her everyone, I am in a course working with Unity, and we have been given a game that we need to modify. I will be as descriptive as possible and provide pictures. The game is very simple. The player spawns in a room with a countdown and has to shoot boxes. Some give points, some add time, some take away time. They player controller we are given can move around, but not jump. I have been trying to code in a jump mechanic to make a more platformer-styled game, but I really struggle when it comes to code because I am more of a 3D artist. I know this question probably gets asked a lot, but from looking at other people’s issues I cannot seem to figure out how to relate what was told to them.
Here is a picture of what the game looks like as it is.
This is the code I am trying to work with. Note that even after adding a rigidbody component, nothing happens. I am not receiving any compiler errors, but the jump function is not working. Any ideas would be great help. Thank you!
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
// public variables
public float moveSpeed = 3.0f;
public bool grounded = false;
public float maxSlope = 60;
public float jumpVelocity = 500;
private Rigidbody rb;
private CharacterController myController;
// Use this for initialization
void Awake (){
rb = gameObject.GetComponent<Rigidbody> ();
}
void Start () {
// store a reference to the CharacterController component on this gameObject
// it is much more efficient to use GetComponent() once in Start and store
// the result rather than continually use etComponent() in the Update function
myController = gameObject.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
// Determine how much should move in the z-direction
Vector3 movementZ = Input.GetAxis ("Vertical") * Vector3.forward * moveSpeed * Time.deltaTime;
// Determine how much should move in the x-direction
Vector3 movementX = Input.GetAxis ("Horizontal") * Vector3.right * moveSpeed * Time.deltaTime;
// Convert combined Vector3 from local space to world space based on the position of the current gameobject (player)
Vector3 movement = transform.TransformDirection (movementZ + movementX);
// Apply gravity (so the object will fall if not grounded)
//Debug.Log ("Movement Vector = " + movement);
// Actually move the character controller in the movement direction
myController.Move (movement);
if (Input.GetKeyDown ("space") && grounded){
rb.AddForce (0, jumpVelocity, 0);
}
}
void OnCollisionStay (Collision col) {
foreach (ContactPoint contact in col.contacts) {
if (Vector3.Angle (contact.normal, Vector3.up) < maxSlope) {
grounded = true;
}
}
} void OnCollisionExit(Collision col) {
grounded = false;
}
}