Adding force in the direction of the mouse
Hi, I'm making a 2.5D game where you can click anywhere on the screen and it will propel your character in that direction and your aim is to not hit the red box. So I'm trying to add force in the direction of the mouse when the player clicks but with what i have now, it's just adding force in seemingly random directions. Here's what i have:
using UnityEngine;
public class Movement : MonoBehaviour {
public Rigidbody rb;
public int clickForce = 500;
void FixedUpdate () {
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0.0f;
mouseDir = mouseDir.normalized;
if (Input.GetMouseButtonDown(0))
{
rb.AddForce(mouseDir * clickForce);
}
}
}
Answer by Orangepolarbear23 · Feb 16, 2021 at 02:56 PM
Hello, @Scandz
Very late, but here is the code I use for that.
gameObject.GetComponent<Rigidbody2D>().AddForce((Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized * moveForce, ForceMode2D.Impulse);
the variable moveForce is how strong you want the force to be.
Answer by Alanisaac · Dec 24, 2017 at 03:45 PM
You're having the same issue described in this UA post. ScreenToWorldPoint is coming back with the location of the camera, so your random direction is actually based on the relative position of the camera in the XY plane. My guess is that you're seeing the object fly towards the "center" of the camera in XY (but not Z).
In a 2.5D game, what you probably want to do is use raycasting instead. This UA post which links to this forum post are helpful. The main idea is to cast a ray from the place the player clicked onto the plane that represents your 2D game world. In your case, it might look something like the code below. Note that you can change the plane
variable depending on how you orient your 2D world.
public class Movement : MonoBehaviour {
public Rigidbody rb;
public int clickForce = 500;
private Plane plane = new Plane(Vector3.up, Vector3.zero);
void FixedUpdate () {
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float enter;
if (plane.Raycast(ray, out enter))
{
var hitPoint = ray.GetPoint(enter);
var mouseDir = hitPoint - gameObject.transform.position;
mouseDir = mouseDir.normalized;
rb.AddForce(mouseDir * clickForce);
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612145113im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player Vibration on collision - AddForce Vs transform.Translate 0 Answers
What is wrong with this script? 3 Answers
Need help for applying force to rigidbody with .AddForce 0 Answers
Object heading towards mouse click/ touch position, script improvement. 1 Answer
coordinates 0, 0 is center, not bottom left corner? 1 Answer