- Home /
Jump is not working in 2D.
Hii..
I am New to Unity I am Creating sample app But right and left is working but jump is not working.
I am Getting Error
There is no 'Rigidbody' attached to the "ball_body" game object, but a script is trying to access it. You probably need to add a Rigidbody to the game object "ball_body". Or your script needs to check if the component is attached before using it.
How to solve this error.
Plz help me
Thank you.
using UnityEngine;
using System.Collections;
public class TankController : MonoBehaviour
{
[HideInInspector]
public bool jump = false;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
private Transform groundDetector;
public bool grounded = false;
void Awake()
{
// Setting up references.
groundDetector = transform.Find("GroundDetector");
}
void Update()
{
// The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
grounded = Physics2D.Linecast(transform.position, groundDetector.position, 1 << LayerMask.NameToLayer("terrain"));
// If the jump button is pressed and the player is grounded then the player should jump.
if (Input.GetButtonDown("Jump") || Input.GetKey("w") && grounded)
jump = true;
}
void FixedUpdate()
{
// Cache the horizontal input.
float h = Input.GetAxis("Horizontal");
if (h * rigidbody2D.velocity.x < maxSpeed)
rigidbody2D.AddForce(Vector2.right * h * moveForce);
if (Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// If the player should jump...
if (jump)
{
rigidbody2D.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}
}
We need to see your code to figure out what is going on. As a guess you are trying to access 'rigidbody.AddForce()' or 'rigidbody.velocity' when you should be using 'rigidbody2D.AddForce()' or 'rigidbody2D.velocity'.
Your answer
Follow this Question
Related Questions
RigidBody2D rotation on y-axis not z-axis 1 Answer
Using Layer Filter Raycast 0 Answers
Endless 2D background 4 Answers
Texture2D Power of 2 0 Answers
MissingComponentException after changing Animator component. 1 Answer