Skip to content Skip to sidebar Skip to footer

Draw a Circle at Mouse Click Unity

When working with second in Unity, you may sometimes desire to make an object interact with the mouse's position in some way.

For example, perchance you want to place a sprite under the cursor?

Maybe you lot want an object to follow the mouse's position?

Or, what if you want an object to look towards the mouse, turning to face it wherever it is on screen?

Simply like moving or rotating an object towards an object'due south Transform position, the position of the mouse on the screen can also be used in the game, past converting it into a earth position.

In this commodity, you'll learn how to become the mouse'southward position in the scene and how y'all tin can utilise information technology to motion and rotate other objects towards the cursor.

Here's what you'll observe on this page:

  • How to get the mouse position in the world in 2d
  • How to motility an object to the mouse's position in 2D
  • How to make a 2nd object move towards the mouse's position
  • Make a 2nd object look at the mouse position
  • Make a second projectile follow the mouse in Unity

Allow's get started.

How to become the mouse position in the globe in second

Getting the mouse position on the screen is relatively straightforward.

This works by getting the Mouse Position property of the Input Class, which returns the pixel coordinates of the cursor on the screen as a Vector 3 value.

Similar this:

          Vector3 mousePosition = Input.mousePosition;        

While the Mouse Position is returned every bit a Vector 3, information technology but includes 10 and Y values (which are the pixel coordinates on the screen).

It's provided as a Vector three for compatibility reasons, allowing you lot to use it with functions that require a Vector iii value. So, while in that location is a Z value in the Mouse Position belongings, it's always zero.

In one case you lot have the mouse's screen coordinates, it's possible to convert them to a real-earth position, using the Screen to World Point function.

Like this:

          Vector2 mousePosition = Camera.master.ScreenToWorldPoint(Input.mousePosition);        

Screen to World Point is a photographic camera function, so you'll need to telephone call information technology from a specific camera or from the Principal Camera, which is simply the get-go camera in the scene with a "Master Photographic camera" tag.

The Screen to World Point function will then render a Vector 3 value, which you can use like any other position in the scene.

How to prepare the depth of the mouse position

While the X and Y values of the Vector 3 that's returned will correspond with the screen position of the mouse, the Z value will be, by default, the same as the camera's Z position.

Which, considering the camera'due south location is behind its Near Prune Plane, is outside of the visible area.

In many cases, this may non exist a problem.

For example, when working in 2d, if you store the outcome of the Screen to World Signal function as a Vector 2 value, the Z value that'south returned is simply not used.

However, if yous apply the Vector three that the Screen to World Point function returns to move an object to the mouse'southward position, without offsetting the z value, information technology will be out of view of the camera.

So, if you're trying to motility an object to the mouse's position, and it keeps disappearing, that could be why.

For this reason, if yous're working with Vector 3 values, you may wish to manually gear up the Z value of the position to a positive value, such as the photographic camera's Near Prune Aeroplane, to make sure that, if you place an object there, that it's always in view:

          Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); mousePosition.z += Photographic camera.main.nearClipPlane;        

For more information about converting the mouse position to a globe position in second and 3D, meet my full guide here:

  • How to catechumen the mouse position to globe infinite in Unity (2d + 3D)

Getting the mouse position using the new Input System

The Mouse Position value is a belongings of the Input Class, which is Unity's legacy system for detecting mouse, keyboard and controller input.

This ways that, if you're using Unity'south new Input Arrangement, this method of getting the mouse'southward coordinates won't work.

Instead, y'all'll demand to utilize the Mouse class, using the Input System namespace, to read the position of the cursor.

Like this:

            using UnityEngine; using UnityEngine.InputSystem; public form GetMousePosition : MonoBehaviour {   void Update()   {     Vector2 mousePosition = Mouse.current.position.ReadValue();   } }          

For more than data on using Unity'due south new Input System, try my complete getting started guide:

  • Input in Unity made piece of cake (a complete guide to the new system)

How to motility an object to the mouse's position in 2nd

Once y'all have the mouse's position in the world, using it to change the position of other objects can be very unproblematic.

For instance, I could utilise the mouse's globe position to place a sprite underneath the cursor.

Like this:

          using UnityEngine; public class FollowMouse : MonoBehaviour {     void Update()     {         Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);         mousePosition.z = Photographic camera.chief.transform.position.z + Photographic camera.main.nearClipPlane;         transform.position = mousePosition;     } }        

By setting the position of the Transform that the script is attached to, the object, in this case, a second sprite, tightly follows the position of the mouse.

This can be useful for placing sprites and objects under the cursor, such every bit a crosshair:

Crosshair following the mouse in Unity

Setting the position of an object, such as a sprite, to the mouse's world position places information technology under the cursor.

How to motility an object to the mouse's position, without lag

While placing an object under the cursor by getting the mouse's position in the world does work, you might discover that there's a lag between the position of the pointer in your operating system and the object on the screen.

Generally speaking, there'southward no getting around this.

While higher frame rates can reduce the corporeality of lag you experience, the mouse is controlled directly by the operating arrangement, meaning it updates independently of the game's framerate.

Because of this, you lot'll always observe some departure between the operating system's cursor and the in-game object, which can be a problem if you're using this method to create a software cursor.

To set it, Unity offers a solution to replace the system's hardware cursor with a custom texture instead, using the Fix Cursor method of the Cursor course.

Like this:

            public Texture2D cursorTexture; void Start() {     Cursor.SetCursor(cursorTexture, Vector2.null, CursorMode.Automobile); }          

While getting the mouse's position in the scene tin can be useful for snapping objects to the cursor'south location, chances are, y'all're more than likely to utilise this method every bit a way to make objects answer to the cursor'due south position in-game.

For example, moving an object towards the mouse.

How to make a 2D object motility towards the mouse's position

Once yous've gotten the position of the mouse in the scene, it's possible to make an object movement towards it.

This works in the same way every bit it would with whatever other object, every bit the mouse position is at present simply a position in a world that can be used as a target to move towards.

For example, using the Move Towards function.

Similar this:

          public float moveSpeed = ten; void Update() {     Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);     transform.position = Vector2.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime); }        

This will make the object that this script is attached to follow the mouse'south position on the screen at a constant speed (in this case x units per second) without overshooting.

The Movement Towards office moves an object towards a target position at a consistent speed.

And, if you lot want to ease the motility of the object so that information technology follows the mouse smoothly, starting and stopping more slowly, you lot can practice that by using Smooth Clammy.

Smoothly move an object towards the mouse (using Smooth Damp)

Smoothen Damp works similar Motion Towards except that it eases the object's movement between its starting point and its target.

The object volition kickoff slowly, accelerate to an optional maximum speed, and dull down as information technology approaches the target position.

Which looks similar this:

Smooth Damp can be used to create a more natural move, where the object will start slow, come up up to speed and slow once again every bit it reaches its target.

Smooth Clammy tin be used to ease many dissimilar types of values. In this case, information technology's a role of the Vector 2 form:

          Vector2 newPosition = Vector2.SmoothDamp(Vector2 currentPosition,      Vector2 targetPosition, ref Vector2 currentVelocity,      bladder smoothTime, float maxMoveSpeed);        

The Shine Damp function takes a Smoothen Fourth dimension, which is, approximately, the amount of time that the movement should accept and, optionally, a Max Movement Speed, which is the maximum allowed speed of the object when completing the movement:

          public float maxMoveSpeed = 10; public float smoothTime = 0.3f;        

Lastly, the Smooth Damp function needs a local value to work from, in this case, a Vector 2, to be able to track the velocity of the object between frames:

          Vector2 currentVelocity;        

In the part, you'll reference the local Electric current Velocity with the ref keyword.

What is the ref keyword in Unity?

The ref keyword in Unity works in a similar fashion to the out keyword, which is used to return additional information from a function.

Nonetheless, while the out keyword is one way, the ref keyword works both ways. It is both set and used by the function.

In this case, the Smoothen Damp role sets and reads the Electric current Velocity value, which is how it can perform a smoothing action over time, even though a new function is called each frame.

Here's how it looks all together:

          public course MoveTowardsSmoothDamp : MonoBehaviour {     public float maxMoveSpeed = 10;     public float smoothTime = 0.3f;     Vector2 currentVelocity;     void Update()     {         Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);         transform.position = Vector2.SmoothDamp(transform.position, mousePosition, ref currentVelocity, smoothTime, maxMoveSpeed);      } }        

How to follow an object at a distance in 2nd

The Motility Towards and Smooth Damp functions both take a parameter for their target position.

Which means that, if y'all desire an object to follow a target in 2d, such as the mouse or another object, simply from a set altitude, all you need to do is offset the position of the target in the direction of the post-obit object.

So how does that piece of work?

Outset, you'll need to know the direction betwixt the two objects.

This is because the outset that you'll demand to add defines a betoken on the path betwixt the target and the post-obit object.

How to go the direction between two objects in 2D

Getting a direction vector between two objects in 2D works by subtracting the position of the origin object from the position of the target then normalising the result.

Or, put merely, start with the target position on the left and subtract the position the direction should kickoff from.

Like this:

          // How to find the direction of an object Vector2 direction = (Vector3 targetPosition - Vector3 myPosition).normalized;        

Normalising the direction vector limits its length to 1 (making it a Unit Vector).

This tin be useful for defining distance in a specific direction as a Unit Vector, multiplied past a distance value, will create a management vector with an exact length.

In this case, getting a unit vector from the mouse position and multiplying it past a Minimum Distance value, such every bit 2 units, volition create a 2 unit commencement in the direction of the object that'due south following the mouse.

Like this:

          public class MoveTowardsSmoothDamp : MonoBehaviour {     public float maxMoveSpeed = ten;     public float smoothTime = 0.3f;     public bladder minDistance = 2;     Vector2 currentVelocity;     void Update()     {         Vector2 mousePosition = Camera.chief.ScreenToWorldPoint(Input.mousePosition);         // Offsets the target position so that the object keeps its distance.         mousePosition += ((Vector2)transform.position - mousePosition).normalized * minDistance;          transform.position = Vector2.SmoothDamp(transform.position, mousePosition, ref currentVelocity, smoothTime, maxMoveSpeed);      } }        

This means that the object volition follow the mouse, but at a distance, never moving closer than the value of Min Altitude to the mouse's position and smoothly moving away if information technology does get too close.

Which looks similar this:

Smooth Damp volition smoothly ease the object to the mouse'southward position while setting a minimum altitude, makes the object follow without getting too shut.

The only reason for working out the management betwixt the two objects in this example is to work out which way the outset should point.

Withal, there are other reasons why you might want to work out the direction of another object.

For example, to make one object expect at another.

Make a 2D object wait at the mouse position

While it seems like a uncomplicated task, rotating i object and so that information technology looks at some other in 2nd can sometimes be tricky.

This is mainly because otherwise convenient functions, such as Wait At, don't always produce the results y'all desire.

  • How to Rotate objects in Unity

A lot of the fourth dimension, when you lot're rotating an object in second, all you really want to do is rotate an object around its forrard Axis, the Z-Axis.

If the object is a apartment sprite, any rotation around the X or Y-Axis could cause the object to go invisible because of its orientation towards the photographic camera.

Because of this, the simplest way to rotate an object in second, is around its Z-Axis, using a unmarried bladder value.

Similar this:

          transform.eulerAngles = new Vector3 (0, 0, float bending);        

Then, all y'all'd need to exercise to rotate the 2nd object is laissez passer in the angle of rotation.

Easy, right?

Except, how practise you lot become the angle between the object that's rotating and the position it'south supposed to exist looking at?

How to get the bending between two 2D objects in Unity

To get the bending between 2 objects, in this case between an object and the mouse position, yous'll need to offset get a direction vector between them.

Just like in the earlier case, getting a direction works past subtracting the starting position from the target.

In this case, that ways subtracting the position of the object that's supposed to be looking at the mouse from the mouse'due south position in the earth.

Like this:

          Vector3 mousePosition = Photographic camera.primary.ScreenToWorldPoint(Input.mousePosition); Vector2 management = mousePosition - transform.position;        

To work out the angle, next you'll need to make up one's mind which way is the object'south forward direction.

For instance, if you lot have a simple 2d pointer:

Then the frontwards direction of that object is to the correct (if you lot want the arrow to point at the mouse correctly that is).

Meaning that the angle you lot'd need to find is the angle between Vector2.right and the direction of the mouse from the object.

Then how can you practice that?

Helpfully, the Signed Angle function in Unity does exactly that.

          float angle = Vector2.SignedAngle(Vector2.correct, direction);        

And so, to rotate the object, all yous need to practice is set up the object's Z rotation to the angle value:

          bladder bending = Vector2.SignedAngle(Vector2.right, direction); transform.eulerAngles = new Vector3 (0, 0, bending);        

Which looks like this:

Calculating the angle between the object and the mouse makes it easier to rotate in second, by only using the Z-Axis.

Angle vs Signed Angle in Unity

There are 2 different functions in Unity for getting an angle betwixt two vectors, Angle and Signed Angle.

While they both piece of work in like ways, returning the smallest of the 2 possible angles between the vectors, the blazon of value they return is slightly different.

For example, Angle returns an unsigned value, meaning it can only be positive. In this example, that means that the angle will e'er exist between 0 and 180 degrees.

For this employ case, that means that, when the angle between the two vectors is less than 0 degrees, or more than 180, the object starts to rotate away from the mouse.

Using the Angle function, instead of Signed Bending, causes the object to rotate away from the mouse at negative angles.

However, Signed Angle returns a value betwixt -180 and 180 degrees, which covers the full circle of rotation, allowing the object to look at the mouse no matter where it is.

Hither information technology is all together:

          public class LookAtMouse : MonoBehaviour {     void Update()     {         Vector3 mousePosition = Camera.principal.ScreenToWorldPoint(Input.mousePosition);                  Vector2 direction = mousePosition - transform.position;         float angle = Vector2.SignedAngle(Vector2.right, direction);         transform.eulerAngles = new Vector3 (0, 0, angle);     } }        

How to rotate a 2nd object smoothly

In the same manner that it'southward possible to smooth the motion of an object towards the mouse, the rotation of an object tin also exist eased.

Typically, there are two ways of doing this.

Either with the Rotate Towards function, which will rotate the object at a consistent max speed (measured in degrees per second)

Like this:

          public bladder turnSpeed = 45; // degrees per second     void Update()     {         Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);         Vector2 direction = mousePosition - transform.position;         bladder bending = Vector2.SignedAngle(Vector2.right, direction);         Vector3 targetRotation = new Vector3(0, 0, bending);         transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), turnSpeed * Time.deltaTime);     }        

Which looks like this:

Rotate Towards volition rotate the object to face the mouse at a consistent speed, measured in degrees per second.

Or, the 2d option is to smoothen the rotation using Smooth Damp.

Using Smoothen Damp will cause the object to plough to look at the mouse in a smoother, more natural motion that is eased at the start and end of its movement.

Like this:

          public float maxTurnSpeed=90; public bladder smoothTime=0.3f;  float bending; bladder currentVelocity;     void Update()     {         Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);         Vector3 direction = mousePosition - transform.position;         float targetAngle = Vector2.SignedAngle(Vector2.right, direction);         angle = Mathf.SmoothDampAngle(angle, targetAngle, ref currentVelocity, smoothTime, maxTurnSpeed);         transform.eulerAngles = new Vector3(0, 0, bending);     }        

Observe that this method uses a specific type of Smooth Clammy, Smoothen Damp Bending, which is a Maths function that allows the angle value to move by 180 degrees.

Using Smooth Damp Angle instead of the standard Polish Damp stops the arrow from going 'the long way circular' when passing the 180 / -180 degrees signal.

Instead, the pointer freely rotates to await at the mouse, no matter where information technology is.

Which looks like this:

Smooth Damp Bending eases the rotation of the object towards its target.

Make a 2D projectile follow the mouse in Unity

The divide methods of moving an object and looking towards the mouse can be combined to make an object follow the mouse position.

For case, to create a missile projectile, that moves towards the mouse, you could combine the method of rotating an object towards the mouse with a simple script that moves the object forwards at a fix speed.

Similar this, for case:

          public float speed = five; void Update() {     transform.Interpret(Vector3.right * speed * Time.deltaTime); }        

The result is a projectile that moves forrad while turning towards the mouse position.

Which looks like this:

Combining the Expect At script with a script that moves the object forward creates a homing missile.

The accuracy of the projectile depends on how quickly it can turn, where a higher turn speed, in degrees per 2nd, ways that the projectile can face the target position sooner, making a tighter turn towards it.

Like this:

Increasing the turn speed makes the projectile turn faster and follow more tightly.

But what virtually physics objects?

If your projectile has a Collider attached to information technology, it's normally a bad idea to motility information technology around using its Transform.

This is to practice with the performance hit of moving a Static Collider, which is merely any object with simply a Collider attached, using its Transform component.

Typically, in 2D, you'll get amend performance when moving it with a Rigidbody component, in this case, set to a Kinematic Body Type.

Screenshot of the 2D Rigidbody Body Type option in Unity (set to kinematic)

Helpfully, you'll still be able to use the aforementioned calculations to manage angle and move as when moving the object using its Transform.

Still, instead of setting the position of the object directly, you'll need to prepare the position and rotation of the Rigidbody using the Move Position and Move Rotation functions.

Similar this:

          public Rigidbody2D rb; public float turnSpeed = 45; public float moveSpeed = 5; void FixedUpdate() {     Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);     Vector3 direction = mousePosition - transform.position;     bladder bending = Vector2.SignedAngle(Vector2.right, direction);     Vector3 targetRotation = new Vector3(0, 0, bending);     rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), turnSpeed * Time.deltaTime));     rb.MovePosition(rb.position + ((Vector2)transform.correct * moveSpeed * Time.deltaTime)); }        

Now it'south your turn

Now I desire to hear from yous…

How are you lot using the mouse position with other objects in your game?

Are y'all turning or moving objects towards the mouse?

And what have yous learned about working with the mouse position in 2D that you know others will find useful?

Any it is let me know by leaving a comment.

Epitome attribution

Become Game Evolution Tips, Direct to Your inbox

Go helpful tips & tricks and master game development basics the like shooting fish in a barrel way, with deep-dive tutorials and guides.

My favourite fourth dimension-saving Unity avails

Rewired (the best input management system)

Rewired is an input management asset that extends Unity's default input organisation, the Input Director, adding much needed improvements and back up for modern devices. Put simply, information technology's much more than avant-garde than the default Input Manager and more reliable than Unity's new Input System. When I tested both systems, I establish Rewired to exist surprisingly easy to use and fully featured, and so I can understand why everyone loves it.

DOTween Pro (should be congenital into Unity)

An nugget so useful, it should already be congenital into Unity. Except information technology'due south not. DOTween Pro is an animation and timing tool that allows you to animate annihilation in Unity. Yous can movement, fade, calibration, rotate without writing Coroutines or Lerp functions.

Piece of cake Save (there's no reason not to utilise information technology)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much then that, for the fourth dimension it would take to build a save system, vs the cost of ownership Easy Save, I don't recommend making your own save system since Piece of cake Save already exists.

reedprecand.blogspot.com

Source: https://gamedevbeginner.com/make-an-object-follow-the-mouse-in-unity-in-2d/

Post a Comment for "Draw a Circle at Mouse Click Unity"