Unity Vector2



C# / Unity Vector2 rotation 2015-03-07 03:20:54 Making a simple asteroids type game to get more comfortable with C# and Unity. I have the asteroids falling from the top of the screen after I instantiate them randomly from spawn points and it all works great. Unity has a Vector2.Distance method that removes the need for us to do any vector math: float distance = Vector2.Distance( transform.position, target.position ); But we’re more interested in understanding the math behind it here.

Vector2 Node

  • Converting from a Vector2 or Vector4. While rare, you may run into situations where you would need to treat the co-ordinates of a Vector2 or Vector4 structure as a Vector3.In such cases, you can simply pass the Vector2 or Vector4 directly into the Vector3, without previously instantiating it.As should be assumed, a Vector2 struct will only pass x and y values, while a Vector4 class will omit.
  • Converting from a Vector2 or Vector4. While rare, you may run into situations where you would need to treat the co-ordinates of a Vector2 or Vector4 structure as a Vector3.In such cases, you can simply pass the Vector2 or Vector4 directly into the Vector3, without previously instantiating it.

The Vector2 node ( shortcut: numeric 2 key ) generates a float2 value containing two float components. This value is usually useful to either define a Constant value which is directly used in shader calculations or to define an exposed Property value that can be modified by the material inspector that uses it. Note: Unity's material inspector for vector2 properties display as vector4 containing four values instead of two, this means the last two values are ignored and do nothing.


Nodes used: Vertex TexCoord, Vector2, Multiply, Time, Add, Texture Sample

Node Parameter Description Default Value
Type A set of ways the value behaves in different situations.
  • Constant: the value is assigned directly in shader code and can't be dynamically changed.
  • Property: the value becomes available in the properties of the material that uses the shader and can be changed in the material inspector or by script.
  • Instanced Property: the value can only be set by script and this defines the shader as an instanced shader. ( see more here: GPU Instancing )
  • Global: the value can only be set by script and this defines a static variable that is shared between all shaders that use it. It's useful to change a value globally.
Constant
Name Name of the property holding the value. This is the name that will be shown in the material properties label if type is set to Property, if not this name is ignored but still useful for organization purposes or to generate a Property Name Vector #
Variable Mode Defines if the current property/global variable is to be created on the current shader.
  • Create: Property and/or global variable is created in the shader
  • Fetch: No variable nor property is registered on shader, useful when p.e. there's need to using global variables declared over a included cginc
Create
Auto-Register If toggled on, creates the property and/or global variable even if not connected to an Output node Off
Precision Defines the amount of bytes the variable can hold, effectively defining how precise the value is. It's usefulness is bond by the hardware specifications necessary. Lowest precision is slightly faster but might produce errors and artifacts.
  • Float: Highest precision, useful for values that can be very high or very low in value (ie: positions, coordinates, etc)
  • Half: Medium precision, in most cases is as good as Float but at half of it's precision
Float
Default Value This is the value the shader currently holds. It's also the default value that is used when a new material is created with this shader. 0
Other Parameters
Property Name This is the variable name that contains the value, this is automatically generated using the Name parameter, it's greyed out and not editable. The generation process removes special characters, whitespaces and adds an underscore at the beginning ( ie: 'My Property Name' becomes '_MyPropertyName' ). This parameter is only visible in Property, Instanced Property and Global types to indicate what's the variable name to use when editing this value by script. _Vector#
Material Value This is the value the node the material currently holds. This parameter is only visible in Property and Instanced Property types which are the two types that let you change the value per material. 0
Attributes
Hide in Inspector Does not show the property value in the material inspector Off
HDR Indicates that a property expects a high-dynamic range (HDR) value Off
Gamma Indicates that a property is specified as sRGB value in the UI and possibly needs conversion according to color space used Off
Per Renderer Data Indicates that a property will be coming from per-renderer data in the form of a MaterialPropertyBlock. Off
Custom Attributes Allows adding custom attributes directly on a textfield -


Output Port Description Type
XY Returns the assigned vector2 value Float2
X Returns only the X component of the vector2 Float
Y Returns only the Y component of the vector2 Float

Math Operators - Vectors

Retrieved from 'http://wiki.amplify.pt/index.php?title=Unity_Products:Amplify_Shader_Editor/Vector2&oldid=3171'

Welcome to this Unity 2D Lerp Tutorial. The Unity 2D Lerp function is often used to move objects along a path or to change values along a path.

However in essence LERP is code word for Linear Interpolation, but what is linear interpolation?

Well interpolation is a mathematical concept which is used to fit points within other points.

Essentially how this works is it takes a set of points and estimates other points for a given x or y value on a graph.

Visually explaining Lerp

Here is essentially what this would look like.

To explain this in brief. The green dots are all the co ordinates that are known.

The red one is a estimation of what the point will look like at that given x or y. So how Lerp works in unity is it will use the first point you give it and the 2nd point you give.

It and create estimations for the time value you pass in. By doing so you can get linear values back between the point 1 and point 2.

With these values you can modify scales, object positions etc, anything that has a linear motion or change.

Here is what the Lerp function definition looks like.

public static Lerp(Vector2 a, Vector2 b, float t);

So in terms of our graph Vector2 a could be the first green dot at the bottom of our graph and Vector2 b could be our last one at the top.

An inconvenient truth free download. The float t, will move us along on the x axis and give us estimates of the line drawn between Vector a and Vector b.

In so doing if we step the time in our Lerp function we would be able to animate, move or modify unity game object.

I hope this makes sense. Can be quite tricky without a mathematical background.

You might begin to understand it more in depth with the following demonstrations.

Demonstrating unity lerp between two positions

Let’s start off with a new unity project. Open up unity hub and create a project called unity 2d lerp tutorial.

So generally when we say translate in the same sentence as lerp we talking about different things really.

Lerp will give us the next co ordinate in our series, where translate will add values to our vector.

It technically would be possible to simulate a lerp with translate. By using a linear function to determine the gradient of our linear graph.

However let us stick to the lerp way of doing a “translate”. This will be using the time function. Let’s start by adding a basic square to our scene.

Unity Vector2

So in the assets tab add a square 2d sprite like this.

Drag it into your hierarchy.

Let’s now create the first basic c# script to handle a “translate”. Go ahead and right click in the assets tab and create a new c# script and call it translate lerp.

Open that up in visual studio code. Utorrent download for mac latest version. Here is what our code is going to look like.

Save that off and attach that to our square by dragging it into the insepector.

Run that and you should get a square moving on the screen. So very simple how this works.

First we have our two vectors point 1 and point 2. We then lerp between the two passing the lerp function our deltaTime * 1.1f. The 1.1f which is our speed at which we want to move our object.

We assign this to a accum variable which is our lerp float over time.

Modifying this code to lerp scale

Unity Vector2

All we now need to do to get unity lerp to scale is change the code to have this instead.

Unity Vector2 Movetowards

Unity lerp smooth step

Want to smooth out the motion try this.

Here we use Mathf.SmoothStep to control the estimation.

That’s it for this tutorial. Going to end it here and in the next section I will be answering some frequently asked questions.

How do I do a smooth lerp in unity?

To do a smooth lerp you can use a smoothing function like Mathf.SmoothStep.

How do I do lerp on scale in unity?

Unity Vector2 Null

To lerp on scale in unity you can simply provide 2 vectors and lerp over the localScale like this.
accum += 1.1f * Time.deltaTime;
this.transform.localScale = Vector2.Lerp(p1,p2, accum);

Unity Vector2 To Angle

How do I do a translate lerp in unity?

You can lerp between two points like this.
accum += 1.1f * Time.deltaTime;
this.transform.position= Vector2.Lerp(p1,p2, accum);

Some final words

I hope this tutorial was useful and helped you understand lerp in a new way. If you want to support me and my content please check out my skillshare course here:

Unity Vector2 Vs Vector3

If you prefer watching video over reading tutorials, why not subscribe to my YouTube channel over here: https://www.youtube.com/channel/UC1i4hf14VYxV14h6MsPX0Yw?sub_confirmation=1

Unity Vector2 List

Here are also some other tutorials you might be interested in: