- Home /
I am trying to launch a 2d object toward the mouse.
I am trying to make a ball launch towards the mouse in 2d, but it is going in directions that don't make much sense.
using UnityEngine;
using System.Collections;
public class Jolt : MonoBehaviour {
public Camera veiw;
public float joltSpeed;
private Vector3 mousecords = new Vector3(0,0,0);
void Update (){
if(Input.GetMouseButtonDown(0)){
mousecords = veiw.ScreenToWorldPoint(Input.mousePosition);
mousecords = new Vector3(mousecords.x,mousecords.y,0);
transform.rotation = Quaternion.Euler(0,0,Vector3.Angle(transform.position,mousecords));
rigidbody2D.AddForce(transform.right * joltSpeed);
}
}
}
Answer by robertbu · May 03, 2014 at 07:18 PM
Here is a bit of rewrite to your code. 'mousecoords' is no longer needed. It assumes the 'right' side of the object this script is attached to is considered the 'forward' side (which is a good guess since you are using 'transform.right' in your AddForce()'. If the 'up' side is considered forward, add 90 to the angle before doing the AngleAxis() rotation.
void Update (){
if (Input.GetMouseButtonDown(0)) {
var pos = veiw.ScreenToWorldPoint(Input.mousePosition);
var dir = pos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
rigidbody2D.AddForce(transform.right * joltSpeed);
}
}
Also dir is never used, and I am not sure if your are using javascript or c#, c# is preferred.
Sorry. Fixed the 'dir' problem. If you are using Vector3.right for your AddForce, then you likely should not be adding 90 degrees. But if you do then:
transform.rotation = Quaternion.AngleAxis(angle+90, Vector3.forward);
But if you make that change, you likely want to use transform.up in your AddForce() call.
Your answer
Follow this Question
Related Questions
Help with 2D physics script 1 Answer
Can anyone tell me what I'm doing wrong here? 1 Answer
Rotate towards velocity (2D) 2 Answers
2D swinging physics. 0 Answers