I’m trying to have an object move to a certain area on tap. I’ve done “research” (looked at 3 articles, 2 videos, then the unity scripting API) and it led me to this.
public int TapDamage = 10;
Vector3 StartPos;
Vector3 p = new Vector3();
Camera c = Camera.main;
Event e = Event.current;
Vector2 mousePos = new Vector2();
void MovingClickBox()
{
if (Input.GetMouseButtonDown(0) == true)
{
mousePos = Input.mousePosition;
mousePos.x = e.mousePosition.x;
mousePos.y = c.pixelHeight - e.mousePosition.y;
p = c.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, c.nearClipPlane));
gameObject.transform.position = p;
}
}
private void FixedUpdate()
{
MovingClickBox();
}
Right now this isn’t moving the object at all and I don’t know how to fix it. Please help. Also, unity is saying that get_main isn’t allowed in a monobehaviour constructor; don’t know what that means but seems useful.
First of all understand the difference between ScreenSpace and GUI space. ScreenSpace has it’s origin at the bottom left of the screen while GUI space has it’s origin at the top left.
Input.mousePosition returns the mouse position in ScreenSpace. The Event class gives the mouse position in GUI space.
ScreenToWorldPoint expects the input point in ScreenSpace. So there’s no need to invert the y axis.
The Event class should only be used in OnGUI. It’s tightly coupled with OnGUI.
Do never check one-time events (like MouseDown, MouseUp) inside FixedUpdate. FixedUpdate is only ever relevant when you deal with continous forces in the physics system. Anything else should or have to be done in Update. FixedUpdate runs in most cases at a slower rate and therefore can “miss” frames. Since one time events are only active for one frame they can not be checked consistently inside FixedUpdate.
Keep in mind that the near clipping plane for a perspective camera is usually extremely small. So your object wouldn’t move much in terms of world space movement. Also if you place an object on the clipping plane it usually wouldn’t be visible since as the name tells you the scene is clipped at the clipping plane.
In a 3d environment you usually want to place an object either a certain distance from the camera or at the raycast hit point in the scene. In a 2d game when using an orthographic camera you may want to set the z position of the returned vector to 0. However from your description and from your code we can’t determine if this is a 2d or 3d problem.