Hi i am new to scripting and i am creating a 3D ball game. I have made a script that works but when hold the space bar instead of jumping once I fly it is something that needs to be fixed for me to make my game This is the script.
#pragma strict
function Start () {
}
function Update () {
rigidbody.AddForce(Input.GetAxis("Horizontal")*10,
Input.GetAxis("Jump")*25,
Input.GetAxis("Vertical")*10);
}
Try this:
function Update () {
var v3 = Vector3(Input.GetAxis("Horizontal")*10.0, 0.0, Input.GetAxis("Vertical")*10.0);
if (Input.GetButtonDown("Jump"))
v3 += Vector3.up * 25.0;
rigidbody.AddForce(v3);
}
Note you should explore the use of Time.deltaTime to scale your movements for different frame rates.
Try:
`bool Grounded(){
float dist = collider.bounds.extents.y;
float max = 0.50f; // to give you some room
return Physics.Raycast(transform.position, -Vector3.up, dist + max);
}
`
also have a look at this: Unity - Scripting API: RaycastHit.distance
You can also try this… Also make sure to give your ground a “Ground” tag through the Inspector. Hope this helps.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
public float speed;
public float jump = 20f;
private Rigidbody rb;
bool isGrounded = true;
float forward;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddRelativeForce(movement*speed);
}
private void Update()
{
bool player_jump = Input.GetButtonDown("Jump");
if (player_jump && isGrounded)
{
rb.AddForce(Vector3.up * jump);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}