- Home /
Question by
AlexReverse · Jul 13, 2018 at 08:00 AM ·
c#jumpspam
Spam jumping.
So I tried to make the player jump but if i press space in the air he still jumps. How do I fix this? Scripts: player script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float maxspeed = 3;
public float speed = 50f;
public float jumppower = 500f;
float size = 0.16f;
public bool grounded;
private Rigidbody2D rb2d;
private Animator anim;
void Start () {
//player movement
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-size , size , size);
}
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(size, size, size);
}
if (Input.GetButtonDown("Jump") && grounded)
{
rb2d.AddForce(Vector2.up * jumppower);
}
}
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
//limiting the speed
rb2d.velocity = new Vector2(h * maxspeed, rb2d.velocity.y);
rb2d.AddForce((Vector2.right * speed) * h);
if (rb2d.velocity.x < -maxspeed)
{
rb2d.velocity = new Vector2(-maxspeed, rb2d.velocity.y);
}
}
}
groundcheck script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundCheck : MonoBehaviour{
private Player player;
void Start()
{
player = gameObject.GetComponentInParent<Player>();
}
void OnTriggerEnter2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerStay2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerExit2D(Collider2D col)
{
player.grounded = false;
}
}
Comment
Answer by tormentoarmagedoom · Jul 13, 2018 at 12:55 PM
Good day.
Where are these scripts attached? Post an image of the inspector please. You are using
player = gameObject.GetComponentInParent<Player>();
So i supose they are not in the same object, they are ina a child and ina parent object.. IF you want to access a a script in the same object, you need
player = gameObject.GetComponent<Player>();
Bye!
Your answer
![](https://koobas.hobune.stream/wayback/20220612170624im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
have 3rd person make a side jump -1 Answers
How to make a ball jump? 2 Answers
Jump when you press on-screen button 1 Answer