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);
}
}
}
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);
}
}
}
}