Hey, Forgive me if I don’t use proper terminology or if this is an extremely simple problem, I’m very new @ C# & Unity.
So, I’m trying to make a script, were my Object cannot jump unless it is currently touching the ground, I’m fairly sure I’ve gone about it in a round-about way, but non the less I feel the solution I came up with, should be working.
The problem is, my “OnColliderEnter(Collider other)” (on line 49-55) which I based off the “OnTriggerEnter” from the Roll a Ball Unity tutorial, does not seem to be registering, when my Object lands back on the ground.
Below, I will post my Script.
using UnityEngine;
using System.Collections;
public class playerMovement : MonoBehaviour
{
public float speed2D;
public float speed3D;
public float jumpSpeed;
private bool jump;
private int jumpAllower;
void Start()
{
jumpAllower = 1;
}
void Update()
{
jump = Input.GetKeyDown(KeyCode.Space);
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement2D = new Vector3(0.0f, moveHorizontal, 0.0f);
Vector3 jumpSize = new Vector3(0.0f, 0.0f , -1.0f);
gameObject.transform.Translate ((movement2D * speed2D) *Time.deltaTime);
if (jumpAllower == 1)
{
Debug.Log("Jump Possible");
if (jump == true)
{
Debug.Log("I jumped");
gameObject.transform.Translate(jumpSize * jumpSpeed * Time.deltaTime);
jumpAllower = 0;
}
}
}
void OnColliderEnter (Collider other)
{
if (other.gameObject.CompareTag("Ground"))
{
jumpAllower = 1;
}
}
}
if anyone could tell me how to get the OnColliderEnter to work, OR, the correct way to do this (or both!) that would be amazing.
Thank you!
I suggest that you still use OnTriggerEnter for this. I don’t have too much experience with Unity myself, but I’ve never gotten OnColliderEnter to work properly over triggers. Also make sure to set the ground as a trigger (found in the collider components), or else this won’t work.
Here’s an example of the fixed script (just that function):
void OnTriggerEnter (Collider other) //Changed to OnTriggerEnter
{
if (other.gameObject.tag ("Ground")) //other.gameObject.tag usually
//works fine
{
jumpAllower = true; //Remember that booleans are useful for things like this. I would redefine this variable as a boolean (use "bool" instead of "int," unless you plan on having more than two options.
}
}
Everything else looks fine.
Salmjak
3
OnTriggerEnter and OnCollisionEnter uses different classes.
OnCollisionEnter uses the Collision class.
OnTriggerEnter uses the Collider class.
So change “Collider other” to “Collision other”! 