Как получить позицию мыши unity
Перейти к содержимому

Как получить позицию мыши unity

  • автор:

Как определить позицию курсора мыши в Unity

Приветствую! При разработке различных игр, нам очень часто приходится отслеживать позицию курсора мыши. И в данной статье мы как раз этим и займёмся.

Сначала нам необходимо найти с помощью свойства Input.mousePosition, текущее положение мыши в пиксельных координатах. А далее, с помощью метода Camera.ScreenToWorldPoint, мы преобразуем положение мыши в пиксельных координатах в мировое пространство. Полученное значение занесём в переменную diference.

Для наглядного отображения того, какие значения хранятся в переменной diference, используем метод Debug.Log():

После запуска нашего скрипта, двигайте мышь по игровому полю, и в окне Console Вы увидите постоянное изменение значений переменной diference, в которой и хранится информация о текущем положении мыши относительно мирового пространства.

Позиция курсора мыши относительно Объекта

Обычно, при создании игр, например какого-нибудь шутера, позицию курсора мыши следует считать не относительно мирового пространства, а относительно вашего персонажа, который производит выстрел. Поэтому код, который мы писали выше, следует немножко отредактировать:

Как Вы могли заметить, мы в конце строки дописали transform.position, в котором хранится информация о положении вашего персонажа, то-есть объекта, который производит выстрел. Таким образом, отняв значения позиции Вашего персонажа, расчёт позиции курсора мыши будет производится НЕ относительно всего мирового пространста, а относительно вашего персонажа — где Ваш персонаж будет являться центром системы отсчёта.

Теперь, после того, как Вы научились получать значение курсора мыши в реальном времени, Вы можете использовать это для вращение вашего персонажа в сторону курсора, или для стрельбы в сторону курсора, или для каких-либо ещё целей.

Input.mousePosition

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

The current mouse position in pixel coordinates. (Read Only).

Input.mousePosition is a Vector3 for compatibility with functions that have Vector3 arguments. The z component of the Vector3 is always 0.

The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height).

Note: Input.mousePosition reports the position of the mouse even when it is not inside the Game View, such as when Cursor.lockState is set to CursorLockMode.None. When running in windowed mode with an unconfined cursor, position values smaller than 0 or greater than the screen dimensions (Screen.width,Screen.height) indicate that the mouse cursor is outside of the game window.

In the following example, the x and y coordinates of the mouse position are printed when the “Fire1” button is clicked.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

How to get mouse position in Unity (Old and New Input System)

Unity Input system returns the mouse position with a single command. But the mouse position cannot be directly used in the game. Unity returns the mouse position in pixels; you need to convert it into world space coordinates to use it in your game. In this tutorial, we will see how to get mouse position in Unity using both the old Input system and the new Unity input System. And also, how to use it in different scenarios of your game.

Mouse Position on screen

Mouse position will be returned to the X and Y axis based on the width and height of the screen.

Step2: Convert mouse position to world Position (both 2D and 3D)

Mouse position obtained in the previous has zero value for the Z axis. When converting mouse position from screen to world point this may cause the object to vanish from the camera view. To avoid this, we give the cameras clip plane distance as the Z value.

On screen and world position

Step3: Use the mouse position in your game

Using mouse position in a 2D game

We can use the X and Y coordinates of our 3D world position to get the mouse position in 2D.

Get Mouse position when the mouse is clicked

In the above example, the code will return the mouse position in all frames. If that is not what you want you can put in a condition like mouse click to get the mouse position. The old input system uses “Input.GetMouseButtonDown(0)” to get the mouse click. You can replace 0 with 1 or 2 depending on which mouse button you want to detect.

Here is an example code

Get mouse position in New Unity input system

Step1: Install the new Input system

  1. Go to Window>Package Manager.
  2. Search for Input System and click install.
  3. You will see a pop up to enable backends click YES.
  4. The editor will restart and the old input system will be disabled.

Step2: Modify the above code to suit the new input system

  1. Add using UnityEngine.InputSystem.
  2. Change Input.mouseposition to Mouse.current.position.ReadValue()

Get mouse button down Unity new input system

Similar to the example in the old input system if you want to get the mouse position only when the left button is pressed you have to replace “Input.GetMouseButtonDown(0)” with “Mouse.current.leftButton.wasPressedThisFrame”.

Here is the sample code for that

Hope it was helpful. If you have any other questions on getting mouse position, please leave it in the comment box below.

3 thoughts on “How to get mouse position in Unity (Old and New Input System)”

This is a good tutorial and it was very helpful. It was also frustrating though since the there are a few capitalisation problems in the code which will result in confusing errors which inexperienced coders, (like myself), may not no how to fix for several minutes.

So for posterity:
public GameObject is correct not gameObject
if statements have no capital I

So if you see this maybe you can go back and fix it and otherwise maybe users can have a look at this comment.
I still think this is a helpful resource! Just needed a little bit of troubleshooting on my part. Thanks.

Looks like the spell check plugin I use is messing with the code. Will check and update it. Thanks for the feedback.

Getting mouse position in unity

I’m trying to move a object to the mouse position. But it’s giving me large x value like 300 but at that place the pre placed object’s x position is -4.

So how can I get the current mouse position?

Bucky's user avatar

5 Answers 5

Input.mousePosition will give you the position of the mouse on screen (pixels). You need to convert those pixels to the world units using Camera.ScreenToWorldPoint().

You can follow this link to learn how to drag a 3d object with the mouse or you can copy this code to move an object from the current position to the mouse position.

The conversion with ScreenToWorldPoint is straight-forward for 2D Vectors:

marts's user avatar

That is the current mouse position. The issue is that your objects are in world coordinates and the mouse is using screen coordinates.

You need to convert the mouse position using Camera.ScreenToWorldPoint().

Ryanas's user avatar

If you wanted to use the new Unity InputSystem you could do the following:

Note that you need to install the InputSystem package for this to work.

ScreenToWorldPoint returns a point in world space, at the provided z distance from the camera.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *