- Home /
how to make my game object to be at mouse position and then to fall at that position?
I want my game object to be at mouse position and fall at that position when spacebar is pressed down, but I cant figure out how to make my game object to stop being at the mouse position. I mean, I want my game object to stop being at mouse position when spacebar is pressed down.
I already added a rigidbody to my game object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Planets : MonoBehaviour
{
public GameObject mercurio;
public void Update()
{
Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, (transform.position.y - Camera.main.transform.position.y) , (transform.position.z - Camera.main.transform.position.z)));
point.z = transform.position.z;
point.y = transform.position.y;
mercurio.transform.position = point
if (Input.GetKeyDown(KeyCode.Space))
{
}
}
}
Answer by Fuzzel_ · Jun 04, 2020 at 01:07 AM
Add a boolean to your MonoBehaviour. Check this boolean inside the Update to skip the code that updates the Planets position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Planets : MonoBehaviour
{
public GameObject mercurio;
public bool attachedToMouse = true;
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
attachedToMouse = false;
}
if (attachedToMouse)
{
Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, (transform.position.y - Camera.main.transform.position.y) , (transform.position.z - Camera.main.transform.position.z)));
point.z = transform.position.z;
point.y = transform.position.y;
mercurio.transform.position = point
}
}
}
I also switched around the check for Spacebar to be done first, otherwise, you will have the Planet attached to your mouse for one additional frame.
Your answer
![](https://koobas.hobune.stream/wayback/20220613000032im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Draw a line and instantiate it as a game object 0 Answers
How rotate a gameobject in Y axis using the mouse position at screen? 1 Answer
AddForce knockback x axis according to mouse.position more then y axis (2D game) 0 Answers
Selecting and Placing objects from GUI 1 Answer
Input.mousePosition is broken, anyway to make it accurate? 1 Answer