so im trying to make it so that if the player is touching something and spacebar is pressed, the player jumps.
if (Input.GetKeyDown(KeyCode.Space) && PlayerController.OnTriggerEnter (collider))
rb.AddForce(new Vector3(0, 10, 0), ForceMode.Impulse);
the code im using. i know it shouldnt work in the state its currently in, but im not sure how to do the collider part. (my player is a ball btw.)
You can’t do it like that. First of all OnTriggerEnter is the complete wrong fuction. You need to use OnCollisionEnter (). Secondly, these are Unity callback functions like void Update or void Start and you can’t call nor create functions in an if statement. Here’s a way to go about this:
bool isTouchingSomething;
float jumpForce = 10.0f
void Update (){
if (Input.GetKeyDown (KeyCode.Space) && isTouchingSomething){
GetComponent (typeof(Rigidbody)).AddForce (new Vector3(0, jumpForce, 0));
isTouchingSomething = false;
}
}
void OnCollisionEnter (){
isTouchingSomething = true;
}
Well, it is just as @William4458 suggested. I used your code to write the script and to show you where to position them exactly:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public Text countText;
public Text winText;
public float jump;
private Rigidbody rb;
private int count;
private bool jumpIsEnabled = true;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
if (Input.GetKeyDown(KeyCode.Space) && jumpIsEnabled == true)
{
rb.AddForce(new Vector3(0, 10, 0), ForceMode.Impulse);
jumpIsEnabled = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
jumpIsEnabled = true;
}
}
}
Keep in mind that you will need to add the tag Ground to your ground object (tags are case sensitive). Also, make sure that both the player and the ground have colliders and they’re both not set as Is Trigger.