Vector2 movetowards unity как работает

от admin

Vector2.MoveTowards

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.

Sumbission failed

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

Parameters

Description

Moves a point current towards target .

This is essentially the same as Vector2.Lerp but instead the function will ensure that the speed never exceeds maxDistanceDelta . Negative values of maxDistanceDelta pushes the vector away from target .

MoveTowards In Unity

A simple way to achieve this is to use Vector2.MoveTowards. This involves getting the current position to the target’s position.

In our 2D SpaceShooter game, we use Vector2, as in we only use two axis here.

In our powerup script, we first need to get a reference to the target, which is the player, and create a bool defining when the powerups move to the player:

Once we press C, we start moving the powerups to the player. In the MoveTowards method, we pass in our current position, the target position, and at what rate, which is our speed * Time.deltaTime.

Now, this format is also the same in 3D games. Except it’s used with Vector3.

transform.position = Vector3.moveTowards(transform.position, _player.transform.position, _speed * Time.deltaTime);

And this is what we get:

And that’s all for this short article, but hope it was helpful! Have a great game-dev day!

Vector2 movetowards unity как работает

Doing 2D top down movement in Unity for your player can easily be achieved with some basic Unity functions and a small script.

First we just going to setup our project. If you don’t want to follow along on this page you can watch the video version below:

Setting up our top down game scene

On the left hand side in the Unity hierarchy right click and create a empty game object. In the inspector add a sprite renderer component.

Copy the following inspector settings, the most import settings is the position and the order in layer must be -100 so the background renders at the back of all your assets in your game scene.

unity 2d move up and down

Add in your background image into the sprite slot and you are ready to go. You now have a nice background in my case I have something that looks like this.

Background image in our scene in the top down

Adding our player to our scene: unity top down movement

Right click in the hierarchy again and create a new game object, rename it and call it Player.

In the inspector add a Rigidbody 2D. Copy the details below:

Player movement settings inspector

You should now have your player in the scene and should look something like this now.

Unity 2D movement top down without our player added

Write our code for our Unity 2D top down player movement controller

First off click on your player game object. Add a new component in the inspector called Player Movement.

Like below this is going to be our 2d character controller :

movement code 2d unity

Now open up your new c# script in visual studio.

We need to now define a few things, we first of all want to control our player movement speed so we will need a player movement variable.

Next we need a target position variable which will be the position we want our player to move towards.

We now need to use some of the built in Unity functions like the Vector2.MoveTowards method. Also we will use time.deltaTime to make sure our movement is frame rate independent.

We will also use ScreenToWorldPoint to convert our mouse position on screen to a point in our world.

We will use the Input class to get the position of our mouse clicks.

Lets get into the code.

Just a quick explanation on how this code works. In the start method we just set a start position to 0.0f and 0.0f just to start with a default position.

Our player initially will also be at 0,0 in our scene so when our game starts our player won’t jump or move.

Next in the update method we need to get our mouse input. So we call Input.GetMouseButtonDown(0) the zero is for the left click on our mouse. We then set our targetPosition to our mousePosition.

We then take those co ordinates to worldPoints the ScreenToWolrdPoint method needs a Vector3 in our case we just pass the x and y position because we are only moving in 2D space.

Then finally we set the transform position of our player by calling Vector2.MoveTowards with the player current position and target position.

We plugin our speed and multiply it by Time.deltaTime to make our movement frame rate independent.

Setting our player movement speed

Once you have saved the script. Close visual studio and now we just need to give our player a movement speed.

unity top down movement rotation

I just chose a speed of 10 which is a decent smooth speed for our player to move.

Well done if you have done everything correctly you should now have your first Unity 2D top down player movement working.

What’s great about this very basic movement script is that it can be used for so many types of games.

Adventure games, rpg style games, if you wanted to stick to complete rpg style you would just have to make sure your Vector in your MoveTowards is locked to one axis at a time because your player can only move up or down and left or right not diagonally.

Weird issues you might have

You might have run into some issues. Where your player might be falling off the screen when you hit play.

In order to make your unity 2d top down gravity work properly you need to set your gravity scale to 0 in your Rigidbody 2D component. Like so:

unity 2d top down gravity

If this tutorial and want to learn more about making 2d games with unity check out our game development section.

So I hope you liked this short tutorial on unity movement and how you can move a player easily in unity using a c# script. There are a lot of ways in which you can create player movement and more.

Some of which is using animation transitions. You could also use a physics based approach propelling your player on screen as well. It’s really up to your creativity. However hopefully this will get you off to a good start.

How to move objects in Unity (3 methods with examples)

Moving an object in Unity can be very straightforward.

It typically involves modifying the properties of an object’s Transform component, which is used to manage a game object’s scale, rotation and position in the world.

However, there are many different ways you can do that…

And while most methods of moving an object in Unity involve modifying the object’s Transform in some way, the exact method you use will vary depending on the type of movement you want to create.

But don’t worry, because in this article, you’ll learn how and when to use each of the different methods for moving an object in Unity, so that you can use the one that’s right for your project.

Here’s what you’ll find on this page:

Let’s get started.

How to move an object in Unity

The most straightforward method of changing an object’s position in Unity is to set it directly, which will instantly move it to a new vector 3 position in the world.

This works by setting the Position property of an object’s Transform component to a new position.

Like this:

Or you can add a vector to an object’s position, to move it by a set amount in a specific direction.

Like this:

Which looks like this:

Adding a vector to an object’s position moves it by that amount.

It’s possible to modify the properties of an object’s Transform from a script that’s attached to it by using the Transform Property:

The Transform property, which is typed with a lower case ‘t’, allows you to reference the Transform component of an object from a script that’s attached to it, without getting a reference to it first.

Which is useful, as it allows you to easily reference, or change, an object’s own position from a script.

Like this:

Modifying a Transform’s position is the most straightforward method of creating movement in Unity.

Either by modifying it directly, over time, or by using the Translate function which allows you to move an object in a specific direction.

How to use Transform Translate in Unity

The Translate function in Unity moves an object by a set amount, relative to its current position and orientation.

Like this:

This is different to simply adding a vector to the object’s position, which would move it relative to world space, while Translate will, by default, move an object relative to its own local space.

This means that, when using Translate, passing in a forward vector will move the object in the direction of its blue axis, the Z-Axis.

When it’s called once, Translate moves an object by a set amount one time.

However, by calling it every frame, it’s possible to create continuous movement.

Like this:

However, there’s a problem with this method.

Because framerates vary between devices and, because each frame often takes a different amount of time to process than the last, the speed of an object’s movement would change depending on the framerate when moving an object in this way.

Instead, multiplying the movement amount by Time.deltaTime, which is the amount of time since the last frame, creates consistent movement that’s measured in units per second.

Like this:

Which looks like this:

Adding a scaled vector over time creates movement.

This works fine, however, it can sometimes be more convenient to manage movement direction and speed separately, by using a Unit Vector to determine the direction and a separate float value to control the speed.

Like this:

This has the same effect as manually typing out the vector, except that the speed is now separate and can easily be changed.

In this example, Vector3.forward is shorthand for (0,0,1) which is the forward direction in world space.

Multiplying Vector3.forward by the speed value, in this case 2, creates the vector (0,0,2) which, when multiplied by Delta Time, creates a forward movement of two units per second.

The result is the same as when manually typing out the vector, except that the speed is now separate and can easily be controlled.

Direction vectors in Unity

A normalised vector, or unit vector, in Unity is simply a vector with a length of 1 that describes a direction. For example the unit vector (0,0,1) describes the forward direction in world space.

Normalised vectors can be extremely useful for calculating distance and speed.

For example, you could multiply a unit vector by 10 to get a position that’s ten units away in a certain direction.

Or you can multiply a vector by a speed value and by Delta Time to create movement at an exact speed in units per second.

While you can type unit vectors manually, you’ll find a number of shorthand expressions for common directional vectors in the Vector 3 class.

For example:

These relate to common directions in world space, however, it’s also possible to get a normalised direction vector relative to an object’s local position and rotation.

Like this:

These can be extremely useful for creating object relative movement.

Such as moving an object forward in the direction that it’s facing.

Like this:

In this case, the object is still moving forward at a speed of two units per second.

The difference is that the direction is based on the object’s orientation, not the world. Which means that if the object rotates, it’ll turn as it moves.

While using a Transform’s local directions can be useful for getting the orientation of a specific object, some functions already operate in local space by default.

Such as the Translate function which, by default, applies movement relative to the object’s local position and orientation, unless you set otherwise.

Which means that, if you use transform.forward with the Translate function, you’ll get a compounded effect, where turning the object throws off its forward vector.

Creating object-relative movement in this way can be useful for adding player controls, where the player can move an object forward, backwards or sideways using input axes, such as from the keyboard.

How to move an object with the keyboard in Unity

To move an object with the keyboard, or with any other input device, simply multiply the direction of movement you want to apply, such as forward, for example, by the Input Axis you want to use to control it.

In Unity, when using the default Input Manager, you’ll find an Input Axis for Horizontal and Vertical movement already set up and mapped to the WASD keys and arrow keys on the keyboard.

  • Input in Unity made easy (a complete guide to the new system)

Each axis returns a value between -1 and 1, which means that you can use the value that’s returned to create a movement vector.

Like this:

This allows you to create object-relative movement controls using the keyboard or any other input device.

Which looks like this:

The Horizontal and Vertical input axes can be used to create movement control.

Even movement controls with Clamp Magnitude

When moving an object using horizontal and vertical axes it’s possible to create diagonal movement that is faster than the speed of movement of a single axis.

This is because the length of the vector that’s created from a forward vector of 1 and a sideways vector of 1 is longer than either one on their own, at around 1.4.

Which means that holding forward and right on a keyboard, for example, would move the player 1.4 times faster than just moving forwards or sideways alone, causing uneven 8-way movement.

So how can you fix it?

One option is to normalise the vector, like this:

However, while this does work, it means that the length of the vector is always one, meaning that any value less than one, such as analogue movements, or the gradual acceleration that Unity applies to digital axis inputs, is always rounded up to one, no matter what.

This might not be a problem for your game if, for example, you’re using the Raw Input values and are deliberately creating tight digital controls.

Otherwise, to also support values that are lower than 1, you can limit the length of the vector instead, using Clamp Magnitude.

Like this:

This will limit the length of the vector to one, while leaving lower values intact, allowing you to create analogue 8-way movement that’s even in all directions.

The Translate function creates movement that’s relative to the Transform component that it’s called from.

However, you may not always want to create player-relative movement.

So how can you move an object in a direction that’s relative to a different object, such as the camera, for example?

How to move an object, relative to the camera

It’s possible to move an object relative to the position of the camera in Unity by using the camera’s forward vector in place of the object’s forward vector.

Like this:

Because the movement is relative to the camera’s position, the Relative To parameter in the Translate function needs to be set to World Space for this to work.

However, there’s a problem…

The forward vector of the camera may, in some cases, be facing at an angle, down towards the player, meaning that any movement that’s applied will also push downwards, instead of along a flat plane, as you might expect.

To fix this, you’ll need to manually calculate the direction between the camera and the object, while leaving out any rotation that you want to ignore.

To calculate a direction, all you need to do is subtract the position of the origin from the position of the target and then, normalise the result.

Like this:

To ignore the difference in height between the camera and the object it’s looking at, simply create a new Vector 3 that replaces the camera’s height with the object’s instead.

Like this:

This will return a direction that is looking towards the object, but isn’t looking up or down.

You can then use the corrected direction that’s created to calculate movement that’s relative to the camera on a flat plane.

Like this:

Which looks like this:

You can create camera relative movement by using the camera’s forward direction in place of the object’s.

By understanding the relative direction of an object, it’s possible to create any kind of movement control that you want.

However, a lot of the time, you may want to move an object in a different way, that’s not directly controlled by the player.

For example, moving an object to a set position or towards another object.

How to move an object to a position in Unity

Generally speaking, there are two different ways to move an object into a specific position.

  1. By speed, where the object moves towards a target at a specific speed,
  2. By time, where the movement between the two points takes a specific amount of time to complete.

The method you use will depend on how you want to control the object’s movement, by time or by speed.

Here’s how both methods work…

How to move an object to a position at a set speed (using Move Towards)

It’s possible to move an object towards another object or a specific position in the scene using the Move Towards function.

Move Towards is a function of the Vector 3 Class that will modify a Vector 3 value to move towards a target at a set speed without overshooting.

Which works great for moving an object towards a position in the world at a speed you can control.

Like this:

The movement can also be smoothed, by using the Smooth Damp function, which eases the movement as it starts and ends.

Like this:

This works by setting the position of the object to the Vector 3 result of the Smooth Damp function, passing in a target, the current position and a reference Vector 3 value, which the function uses to process the velocity of the object between frames.

This can be useful for smoothed continuous movement, where the target position may change from one moment to the next such as when following the player with a camera.

Such as in this example of a smooth camera follow script using Smooth Damp:

In this example, the camera will smoothly move towards the player and turn to face them, while keeping at a height of 3 units and trying to stay at a distance of 5 units away.

Move Towards works great as a way to move an object towards a position dynamically.

This is because the movement is speed-based, and can be controlled even if the target position moves or is unknown.

However, there are many times where you may simply want to move an object to a known position over a set period of time.

Such as moving a platform, or opening a door.

So how so you create time-based movement in Unity?

How to move an object to a position in a set time (using Lerp)

Lerp, or Linear Interpolation, is used to find a value between a minimum and maximum based on a position value, ‘t’, which is a float between zero and one.

The value that’s returned depends on the value of t where, if t is 0 the minimum value is returned, while 1 returns the maximum value.

Any other value in-between 0 and 1 will return a representative value between the minimum and maximum ends of the scale.

Typically, Lerp is used to change a value over a period of time, by incrementing t every frame to return a new value on the scale.

This can be used to change a colour, fade an audio source or move an object between two points.

  • The right way to use Lerp in Unity (with examples)

It works by passing in the amount of time that has elapsed during the Lerp, divided by the total duration. This returns a 0-1 float that can be used for the t value, and allows you to control the length of the Lerp movement by simply choosing how long you’d like it to take.

Like this:

Vector3.Lerp works in the same way except that, instead of returning a float, it returns a point in the world between two others, based on the t value.

This can be useful for moving an object between two different positions, such as a door with an open and closed state.

Like this:

In this example, I’ve used a coroutine to move the door object up by a set distance from the door’s starting position, whenever the Operate Door function is called.

Which looks like this:

Lerp can be used to move an object between two states, such as the open and closed positions of a door.

This creates a linear movement from one position to another, however, it’s also possible to smooth the Lerp’s movement using the Smooth Step function.

This works by modifying the t value with the Smooth Step function before passing it into Lerp.

Like this:

This will ease the movement of the object at the beginning and end of the Lerp.

How to move an object to a position using animation

Depending on how you’d like to control the movement of objects in your game, it can sometimes be easier to simply animate the object you’d like to move.

This typically involves modifying properties of an object and storing them in Keyframes, which are then smoothly animated between over time.

For example, you could use animation to move an object between two points, such as a floating platform.

This would need three Keyframes to work, one for the starting position, another for the platform’s end position and a final Keyframe to return the platform to its original position, looping the animation.

To animate an object you’ll need to add an Animator and an Animation Clip, which you can do from the Animation window.

Add an Animator dialogue in Unity

Next, select a position on the Animation Timeline, this will be the position of the 2nd Keyframe, when the platform is furthest away..

Animation Timeline selection in Unity

Assuming that, at zero seconds, the platform is at its starting position, this will be the halfway point of the animation which, in this case, is 5 seconds.

Next, enable Keyframe Recording by clicking the record button:

Enable keyframe recording

While Keyframe Recording is enabled, any changes you make to an object will be saved to a Keyframe at that timeline position, such as changing its position:

Screenshot - Recording transform changes to Keyframe

Create a final Keyframe at ten seconds, setting the object’s position to its original values to complete the animation (remembering to disable Keyframe Recording when you’re finished).

Animation Timeline selection in Unity with Keyframe Recording enabled

The end result is a platform that moves smoothly, and automatically, between its Keyframe positions.

These methods work well for creating controlled precise movements in Unity.

But, what if you don’t want to control an object’s movement precisely?

What if you’d rather push, pull or throw an object, to create movement using physical forces instead?

How to move an object using physics

Most rendered objects in Unity have a Collider component attached to them, which gives them a physical presence in the world.

However, an object with only a Collider is considered to be static, meaning that, generally speaking, it’s not supposed to move.

Читать:
Как найти малую полуось орбиты

To actually move an object under physics simulation, you’ll also need to add a Rigidbody component to it, which allows it to move, and be moved, by physical forces, such as gravity.

You can also move a physics object by applying force to its Rigidbody using the Add Force function.

Like this:

This works in a similar way to the Translate function except that the vector you pass in is a physical force, not a movement amount.

How much the object moves as a result will depend on physical properties such as mass, drag and gravity.

There are two main ways to apply physical force on an object.

You can either apply force continuously, building momentum and speed over time, or all at once in an impulse, like hitting an object to move it.

By default, the Add Force function applies a continuous force, like a thruster gradually lifting a rocket.

Like this:

Notice that I’ve used Fixed Update, and not Update, to apply the force to the object.

This is because Fixed Update is called in sync with the physics system, which runs at a different frequency to Update, which is often faster and can vary from frame to frame.

Doing it this way means that the application of force is in sync with the physics system that it affects.

Alternatively, you can also apply force in a single burst, using the Impulse Force Mode.

Like this:

This will apply an amount of force to an object all at once:

Add Force can be used to push objects gradually, or apply force in a single hit, like this.

Which can be useful for faster, more explosive movements, such as making an object jump.

Now it’s your turn

How are you moving objects in your game?

Are you moving them using their Transform components?

Or are you moving them with physics?

And what have you learned about moving objects in Unity that you know others will find helpful?

Whatever it is, let me know by leaving a comment.

by John Leonard French

Game audio professional and a keen amateur developer.

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

My favourite time-saving Unity assets

Rewired (the best input management system)

Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.

DOTween Pro (should be built into Unity)

An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (there’s no reason not to use it)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.

Comments

Very good article, as always. If I got it when I started with Unity, it would have saved me a lot of time. Thanks for your efforts.
Btw I subscribe to newslleter but don’t get notifications of new articles. Just tips with links to older content. Is it supposed to work this way? I would like to get notifications of fresh articles

Thank you! The newsletter is ordered, so you’ll get a mix of topics including some content that’s not on the site, but if you’re getting content that you’ve already read about I’ll maybe change how that works. Thanks for the feedback.

Your Topics start becoming a references for me,thank you sir for the efforts and please keep posting

Glad it helped! Thank you.

That was very helpful, thank you so much

one frame == about .05 of a second.

transform.position == with an approx average of 3-5 1×1 tiles moved per frame.

transform.Translate == about the same as transform.position.

There is no instant move command with unity that I’m aware of. Unfortunately unity is notoriously well known for being “half baked” like this. However, unity is free, soooo you get what you pay for and shouldn’t complain IMO.

Every movement command just gives you the illusion of an “instant” movement by moving the object super fast and hoping that no one notices.

The best results I’ve been able to come up with is by sticking my transform.position command inside of a while loop. For whatever reason, this reduces the total frames that a GameObject is seen moving from posA to posB by 60% to 80%.

Example 1: Using a normal transform.position command
-If you have to move 300 1×1 tiles on the Y axis and 900 1×1 tiles on the X axis and you do the standard transform. position to move your object (you supposedly get a 1.4 speed boost because its a diagonal movement, i haven’t seen that to be true yet but who knows). Anyways, it will take somewhere around 351 frames to fully move your object that distance.
And during all 351 frames of that movement your GameObject will be teleporting all over and maybe acting goofy depending on what you’ve got going.

Example 2: Placing your transform.position command inside of a while Loop
– Take the same 300 by 900 map and while loop your transform.position and it will only expose your GameObject to the players eyes for somewhere around 15-50 total frames after fully moving your object that same distance. Meaning that players are 60% to 80% less likely to see your moving gameObject.

This is some dirty spaghetti code that i cooked up once as an example.
Although the code is dirty as sunflower seeds, the fact remains that while loops == much cleaner transform.positions. And there is no such thing as a truly bonafide
“instant move command” in Unity as far as I know at this time anyways.

private IEnumerator MovePlayer(Vector3 direction)
loopCounter = 0;
print(“START”);
isMoving = true;
float elapsedTime = 0;
origPos = transform.position;
targetPos = origPos + direction;
timeToMove = saveTimer;

while(elapsedTime = 900 || currentPosition.x <= 0 || currentPosition.y = 300)
cantClaim = true;
wrappedAround = true;
targetPos = detector.currentPosition;
currentPosition.z = 1;
transform.position = currentPosition;

if(currentPosition.x 0)
currentPosition.x = 900 -.1f;
transform.position = currentPosition;
>
else if(currentPosition.y 0)
currentPosition.y = 300 -.1f;
transform.position = currentPosition;
>
else if(currentPosition.x < 0 && currentPosition.y 300 && currentPosition.x 900 && currentPosition.y 300 && currentPosition.x > 900)
currentPosition.x = .1f;
currentPosition.y = .1f;
transform.position = currentPosition;
>

currentPosition = transform.position;
>
if(currentPosition.x 0)
cantClaim = false;
>
if(currentPosition.y > 0 && currentPosition.y < 300)
cantClaim = false;
>
print(«AFTER = CURRENT POS = » + currentPosition + » / TARGET POS LOOP COUNTING END»);

>//END OF move unit

Sorry, but what you’ve said isn’t correct. To address some of the points in your comment:

  • Framerate is variable, and unless your game is running at a locked 20fps, frame time isn’t going to be 0.05, it’s going to vary every frame. Which is why you always need to use Delta Time when applying a movement amount
  • Changing an object’s position using its transform does essentially teleport it to that position, there’s no behind the scenes movement that I’m aware of.
  • The 1.4 diagonal boost you mentioned is to do with the adding up of 2 input axes, where the result is a diagonal vector with a length of 1.4, not 1. It’s usually fixed by normalising the input vector.
  • There should be no reason why placing the same function in a while loop changes how it operates. It’ll still be called by Update, or whatever event function you place it in. The only difference is the condition of the while loop.
  • In your example, you haven’t scaled your movement by Delta Time. If you’re trying to move an object without Delta Time, you’re going to get inconsistent movement.

I feel like what you’ve done is made something very complicated when it really doesn’t need to be, the simplest way to move an object in Unity is to apply a movement amount, that’s scaled by delta time, every frame. However, if I’ve missed something and you’re having a problem with movement in Unity, then please tell me about it, describe what’s happening that shouldn’t be so that I can understand what you’re experiencing and why.

Please note, however, that this is, very deliberately, not a Unity forum and I have a strict comment policy regarding comments that could be confusing or unhelpful to others.

All the best,
John.

Hi John,
This is very interesting and informative. I am just starting a project where I need to move an object up and down, side ways and also diagonally and I was wondering which method is best to do this and I came across this article. You have explained everything beautifully and saved me a lot of time. I am just a little unsure about how to move diagonally but I think I will get if I read your article a couple of times.
Thank you.

Thank you, I’m so glad it helped. Normalizing a vector that’s made up of the two directions that will make the diagonal (e.g. (1,1,0) for example) should give you the diagonal movement you want. Like this: Vector3 movementAmount = new Vector3(1, 1, 0).normalized;

Thank you and I appreciate your quick reply

Hi John,
Sorry to butt in again.
I am able to get the movement diagonally. I need to move it at various speeds starting from 45 meters/second. Is a unit in Unity equals to 1 meter? So if I use 45 * Time.deltaTime do I get my speed as 45m/sec? What if I wanted to use, say, 300 deg/sec; can the units be changed in Unity?
Thank you.
Vasu

Yes, 1 unit in the world is meant to be 1m (more info) so 45 * delta time is 45m per second. It will also work with rotation, yes, so you can create degrees per second with the same technique.

Really Awesome Work John French. I read your about us and it feels like i am reading mine. but it motivates me a lot. Thank you for such a great contribution.

Excellent information. Thank you.
In my project, for the graphics part, I just need to move alphabets at high speeds from left to right in all directions. No collisions with anything. So I used 2D /sprites/square and put the alphabets on it.
I used every possible move method you have indicated above to move my alphabets (not animations, yet). The alphabets moved smoothly in all directions. No issues.
It works fine for low speeds but once I use speed 30 and above, instead of one alphabet moving across the screen, it doubles( I am sorry I don’t know the name for this: doubling, bunching, lagging or some such thing) and moves across the screen. For example, instead of just one image(in this case letter ‘C’) going from left to right, it goes as below in bunches, from left of the screen to the right.

Thinking that it might be an issues with my monitor, I tried different devices but this behavior persists across all of them.
Much appreciated if you could show me a way to overcome this bizarre movement behavior.

It sounds like a visual problem but I don’t know that for sure. If you don’t mind sharing your code email [email protected] and I will take a look.

Thank you. I just emailed the code and a screenshot of the issue.

This is such an informative and clearly explained article, what an excellent overview.

I had become quite confused with all the different ways to move objects in Unity, and here it’s all made perfectly clear.

Thank you very much. I’ve bookmarked it and will subscribe to your newsletter!

2D Procedural Animation In Unity

I recently took part in the Ludum Dare 46 and attempted to tackle procedural movement as part of my game, The Dark Cave. This post explores how I did that and how you can use it in your games.

Check it out on Browser and Windows Desktop here.

Moving The Body

Before we move the legs we need to get the body moving.

Create a new script and attach it to the main parent-transform of your creature/character.

We only want to move the body on the X-axis as we’ll be setting up the height later, which is why set the target y position to the current position of the body.

Rigging The Legs And Inverse Kinematics

Unity has made it very easy to create bone rigs and add inverse kinematics (IK). By using IK we ensure all other joints move correctly when you move the feet, which makes our lives a lot easier.

Using the Unity’s rigging tools is a whole blog post in itself. Luckily Brackeys have made a fantastic video on 2D skeletal animation and IK, which I followed followed during the jam.

Once you have rigged your legs and set up IK, you should be able to move the feet and the rest of the leg will move nicely with it.

One Step At A Time

Keeping The Legs In One Spot

Currently our creature’s feet follow the body, which we don’t want to happen.

To solve this we need to lock the feet to the ground.

Create a new script which controls the leg. You will need to attach this script to each leg you add. In the script we create a target position for the current spot we want the foot to remain and constantly move the foot towards that position in Update().

Now the feet should remain planted on one spot, even if we move the body.

Setting The New Target Point and Ground Detection

Next we need to work out where we want each leg to step. Create a new empty gameobject for each leg and make them child objects of the body. This ensures they move with the body. These will be our desired target points (shown in red).

The new Target points move with the body so we don’t need to set their X position. However, we do need these points to snap to the ground. We can achieve this by performing a raycast above the target point down towards the ground, then setting the Y position of the target point to the hit Y value.

In my raycast I also check for the ground layer so that the creature does not step on other objects — this is optional.

The final result should have the desired target points moving with the body and snapping to the ground.

Take A Step (Or A Skate?)

Our creature is now ready to take his first step! Well at this point the movement will look more like skating.

Check the distance between the currentTarget (the positon we use to hold the foot in place) and the new Desired Target. If the distance threshold is met, it’s time for our creature to take a step.

Set the currentTarget position to the DesiredTarget’s position and the foot will move towards the currentTarget’s position.

This should result in the creature taking step-like slides towards as it moves with each step landing on the ground.

Step Height and Animation Curves

Scooting around is fun, but lets add some height to the steps.

There’s a few ways you can approach this, but I like to offset the step height using Animation Curves as they’re visual and give you a good level of control over how the steps rise and fall.

First we create an animation curve and a float to handle time at the top of our script.

We then check the distance between the foot and the current target.

If the distance is greater than 0.1f we need to move the foot towards the currentTarget’s position and add current height of the animation curve to the y position of the foot.

We set the timer using Time.delta time so that it scrolls through the animtion curve in real-time and that’s how we get our step height.

If the distance is less than 0.1f we just clamp the foot to the currentTarget’s position.

Currently our step won’t look any different and the legs will still be gliding across the floor.

We need to set up the AnimationCurve in the inspector. Click on the box next to your yCurve animation curve and the curve editor window should appear.

At the bottom of the window are a few curve presets. I use the flat line preset as a starting point (first option), but you can use whatever you like.

— Left click on a key point and move the handle to change the curve direction of that point.

— You can add new key points anywhere on the line by right-clicking and clicking ‘Add Key’.

— Click and drag a key point to reposition.

The X-axis of the graph determines the amount of time and the Y axis is the height of our step. Play around with differing shapes, speeds and heights until you have something you like.

I wanted my creature to feel like it was stalking the player and trying to be quiet, so I left the step height quite low for mine.

It’s Alive!! — Closing Notes and Next Steps

Our creature should now be walking properly, with its feet connecting to the ground regardless of how bumpy the terrain is.

There’s plenty you can do to expand on this:

Use animation curves to make the body bob up and down whilst idle.

Add layer masks to your ground detection rays so that the creature only walks on certain surfaces, or maybe allow it to walk on everything and cause havoc!

Add extra raycast checks infront of and behind the creature to see if the ground stops to prevent it from walking off ledges.

Move the rear DesiredTarget points in closer to the creatures body to give it a more creepy sense of movement.

These are just a few examples of what you can do with procedural animation. I really enjoyed experimenting with movement during the LudumDare and it’s certainly something I want to experiment with more and I can’t wait to see what you make.

Unity 2D movement top down tutorial: Guide to player movement

Unity 2D movement top down tutorial: Guide to player movement

Doing 2D top down movement in Unity for your player can easily be achieved with some basic Unity functions and a small script.

First we just going to setup our project. If you don’t want to follow along on this page you can watch the video version below:

Setting up our top down game scene

On the left hand side in the Unity hierarchy right click and create a empty game object. In the inspector add a sprite renderer component.

Copy the following inspector settings, the most import settings is the position and the order in layer must be -100 so the background renders at the back of all your assets in your game scene.

unity 2d move up and down

Add in your background image into the sprite slot and you are ready to go. You now have a nice background in my case I have something that looks like this.

Background image in our scene in the top down

Adding our player to our scene: unity top down movement

Right click in the hierarchy again and create a new game object, rename it and call it Player.

In the inspector add a Rigidbody 2D. Copy the details below:

Player movement settings inspector

You should now have your player in the scene and should look something like this now.

Unity 2D movement top down without our player added

Write our code for our Unity 2D top down player movement controller

First off click on your player game object. Add a new component in the inspector called Player Movement.

Like below this is going to be our 2d character controller :

movement code 2d unity

Now open up your new c# script in visual studio.

We need to now define a few things, we first of all want to control our player movement speed so we will need a player movement variable.

Next we need a target position variable which will be the position we want our player to move towards.

We now need to use some of the built in Unity functions like the Vector2.MoveTowards method. Also we will use time.deltaTime to make sure our movement is frame rate independent.

We will also use ScreenToWorldPoint to convert our mouse position on screen to a point in our world.

We will use the Input class to get the position of our mouse clicks.

Lets get into the code.

Just a quick explanation on how this code works. In the start method we just set a start position to 0.0f and 0.0f just to start with a default position.

Our player initially will also be at 0,0 in our scene so when our game starts our player won’t jump or move.

Next in the update method we need to get our mouse input. So we call Input.GetMouseButtonDown(0) the zero is for the left click on our mouse. We then set our targetPosition to our mousePosition.

We then take those co ordinates to worldPoints the ScreenToWolrdPoint method needs a Vector3 in our case we just pass the x and y position because we are only moving in 2D space.

Then finally we set the transform position of our player by calling Vector2.MoveTowards with the player current position and target position.

We plugin our speed and multiply it by Time.deltaTime to make our movement frame rate independent.

Setting our player movement speed

Once you have saved the script. Close visual studio and now we just need to give our player a movement speed.

unity top down movement rotation

I just chose a speed of 10 which is a decent smooth speed for our player to move.

Well done if you have done everything correctly you should now have your first Unity 2D top down player movement working.

What’s great about this very basic movement script is that it can be used for so many types of games.

Adventure games, rpg style games, if you wanted to stick to complete rpg style you would just have to make sure your Vector in your MoveTowards is locked to one axis at a time because your player can only move up or down and left or right not diagonally.

Weird issues you might have

You might have run into some issues. Where your player might be falling off the screen when you hit play.

In order to make your unity 2d top down gravity work properly you need to set your gravity scale to 0 in your Rigidbody 2D component. Like so:

unity 2d top down gravity

If this tutorial and want to learn more about making 2d games with unity check out our game development section.

So I hope you liked this short tutorial on unity movement and how you can move a player easily in unity using a c# script. There are a lot of ways in which you can create player movement and more.

Some of which is using animation transitions. You could also use a physics based approach propelling your player on screen as well. It’s really up to your creativity. However hopefully this will get you off to a good start.

Похожие статьи