3
\$\begingroup\$

I created some MenuItemfunctions for navigating, which are currently displayed on the menu toolbar. The C# code:

using UnityEditor;
using UnityEngine;

public class Menu : MonoBehaviour {

static void rotateView(Quaternion rotation) {
    SceneView.lastActiveSceneView.LookAt(SceneView.lastActiveSceneView.pivot, rotation);

    SceneView.lastActiveSceneView.Repaint();
}

[MenuItem("View/Front _1")] // FRONT
static void FrontView() {
    rotateView(Quaternion.Euler(0, 180, 0));
}

[MenuItem("View/Back &1")] // BACK
static void BackView() {
    rotateView(Quaternion.Euler(0, 0, 0));
}

// Few more similar functions

}

I came from Blender, where there are shortcuts opening a context menu on the cursor position like this one, opened after pressing U:

Blender context menu

What I want to do is displaying a context menu after pressing P which would display a list of implemented MenuItems. Is something like this possible in Unity?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You can use ScreenToWorldPoint to convert your mouse positions to 3D coordinates.

Also ScreenToViewportPoint converts your mouse positions to normalized 2D coordinates on current viewport.

Usage:

ReferenceCamera.ScreenToWorldPoint(mouseX,mouseY,distanceFromCamera)

Where

mouseX = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).x

mouseY = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).y

  • ScreenToViewportPoint gives you a value between 0 and 1 normalized for the screen you are playing in. Very useful for placement of UI elements on HUD. This is probably what you are looking for.
  • ScreenToWorldPoint is used to get world position. This is useful if you want to create an explosion at x distance from screen for a game with orthographic projection.

Create a HUD. Attach it to camera. Check ScreenToViewportPoint and calculate if the menu should spawn to bottom-right/bottom-left/top-left/top-right so it doesnt go out of bounds. You can track selections through same method.

\$\endgroup\$
1
  • \$\begingroup\$ This answer would be more useful if it elaborated on the steps of "Create a HUD" and how one would attach a HUD to the scene view camera, not the MainCamera object that renders the game. \$\endgroup\$
    – DMGregory
    Commented Mar 9, 2023 at 13:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .