- Home /
Question by
TheHgang · Oct 17, 2017 at 03:44 PM ·
jumping objectclick objects
Plese help me. I want clicked object to jump . not all game objects and prefabs. i tried using raycast. its 2d game. plese correct my code.
sing UnityEngine; using System.Collections;
public class jumpscript : MonoBehaviour {
private Rigidbody2D myRigidBody;
public float jumpForce;
public bool isjumping;
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
if (hit.rigidbody != null)
hit.rigidbody.AddForce (Vector2.up * jumpForce);
}
}
Comment
Answer by Lairinus · Oct 17, 2017 at 04:38 PM
Your code right now is searching for any Rigidbody from any RaycastHit, so it makes sense that everything would be jumping. By adding a conditional check, we can move any specific rigidbody that we want, and only that one. In this case, this code will only move your "myRigidBody" object. As you will see, I've only added one conditional statement.
private Rigidbody2D myRigidBody;
public float jumpForce;
public bool isjumping;
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
if (hit.rigidbody != null && hit.rigidbody == myRigidBody)
hit.rigidbody.AddForce (Vector2.up * jumpForce);
}
}
Your answer
Follow this Question
Related Questions
Jump over object help 1 Answer
Basic Jump Pad help 2 Answers
i want to make a ball jump 1 time please can i have someones script? 0 Answers
Popup Textures for game objects 1 Answer
click object to open door help 0 Answers