Move an Object by clicking on it
Hello guys, i've been searching for somedays now and didnt find my answer. I'm trying to make a 2D game,where when i click in a ball make it moves, but i'm getting problems to know the position of the mouse and the object. This is what i have:
using UnityEngine;
using System.Collections;
public class moveBubble : MonoBehaviour {
Vector2 mousePos;
Vector2 ballPos;
Vector2 forceDir;
float factor = 0.003f;
Rigidbody2D objFis;
void Start()
{
objFis = objFis = this.gameObject.GetComponent<Rigidbody2D>();
}
IEnumerator OnMouseUp ()
{
mousePos = Input.mousePosition;
ballPos = this.gameObject.transform.position;
forceDir = mousePos - ballPos;
objFis.AddForce(forceDir * factor);
yield return StartCoroutine(StopBall(4.0F));
}
IEnumerator StopBall(float waitTime) {
yield return new WaitForSeconds (4);
objFis.velocity = Vector3.zero;
}
}
The direction is not working at all, i dont know if i should use a raycast to know where the mouse is on the object, and even the force its too much. I already tried to make a lot if conditions, and add an expecific force to the object, but its just so many ifs that feels wrong doing it. The ball has a physics2d, and 0 gravity. Its a ballon in the space basically The logic is simple, if i click in the button of the ball, it moves up, etc... i want all the directions
Can anyone help me? Thanks!
Answer by JedBeryll · Dec 04, 2015 at 11:12 PM
Yes raycasting is the best way to do it. Input.mousePosition will give you wrong coordinates because its a screenpoint coordinate. (on the screen the y works backwards)`enter code here` I have something similar:
public Caster caster; // this is a reference to my raycaster script
void Update() {
if (caster.hit.collider != null) { //make sure you actually hit something otherwise you get errors
mousePos = caster.hit.point;
}
}
The Caster has a RaycastHit hit; variable which i set every frame. So if you want to decide where the ball should go by clicking on it and deciding if its up, or down or whatever compared to the ball's center:
ballPos = this.gameObject.transform.position;
forceDir = mousePos - ballPos;
forceDir.Normalize(); // do this to make sure your vector has a magnitude of 1 - this causes the ball to move with the intended speed
objFis.AddForce(forceDir * factor);
Now you should scale up your factor because it's going to move unnoticably slow. Hope this helps!
Thanks a lot! That worked :D i only had to change the forceDir = ballPos - mousePos to get what i really wanted :) thank you
Your answer
Follow this Question
Related Questions
Unrealistic 2D Bouncing 2 Answers
Problem getting dropped bombs to behave properly 0 Answers
2D ledge grabbing -1 Answers
Max velocity and constant acceleration 0 Answers