2D shape with 4 sides: General Data Protection Regulation(GDPR) Guidelines BYJU’S
Posted onSides and Vertices
JavaScript is disabled in your browser.
To make full use of our website,
enable JavaScript in your browser.
Try 30 days for free
Discover why over 1.2 MILLION students choose sofatutor!

Math

Geometry

Basic Shape Attributes
 Sides and Vertices of Shapes
Rating
Ø 5.0 / 3 ratings
You must be logged in to be able to give a rating.
Wow, thank you!
Please rate us on Google too! We look forward to it!
Go to Google
The authors
Team Digital
Basics on the topic
Sides and Vertices of Shapes
Content
Vertex Geometry – Sides and Vertices
Most 2D shapes have sides and vertices. So what are sides and vertices? Let’s find out all there is to know about sides and vertices in this text. A side is a straight line that makes up a closed 2D shape.
A vertice, or vertex when we are talking about just one, is where two sides meet to form a corner.
Sides and Vertices on Squares and Trapezoids
Squares and trapezoids are a type of quadrilateral. How many sides and vertices does a quadrilateral have? Quadrilaterals have 4 sides and 4 vertices, so when someone asks you what shape has 4 sides and 4 vertices, you can tell them all quadrilaterals do! Therefore, a square and trapezoid are examples of a shape with 4 sides and 4 vertices.
Sides and Vertices on Pentagons
How many sides and vertices does a pentagon have? A pentagon is a shape with 5 sides and 5 vertices, so when someone asks you what shape has 5 sides and 5 vertices, you can tell them pentagons do!
Sides and Vertices on Circles
How many sides and vertices does a circle have? A circle is a special case, because it has 0 sides and 0 vertices, so when someone asks you what shape has 0 sides and 0 vertices, you can tell them a circle!
Sides and Vertices of 2D Shapes – Summary
Most shapes have sides and vertices. You can use these to help identify 2D shapes. A side is a straight line that makes up a closed 2D shape. A vertice, or vertex, is where two sides meet to form a corner. In this text we learned that squares and trapezoids have four sides and four vertices, whereas a pentagon has five each. How many sides and vertices does a triangle have? Triangles have three sides and three vertices, hence the name tri (=three).
The table below shows an overview of shapes, their number of sides and their vertices.
Name of the Shape  # of Sides and Vertices 

triangle  3 
square, rectangle, trapezoid  4 
pentagon  5 
hexagon  6 
If you want more you will find interactive exercises, worksheets and more activities on sides and vertices on two dimensional shapes after the video.
Transcript
Sides and Vertices of Shapes
Nico has found an old game console in the attic. «Ohh, what is this?» «Hmm. I wonder?» It looks like a game has started on the console! However, Nico needs to learn about sides and vertices of 2D shapes to play the game. To help Nico play the game, let’s learn about sides and vertices of 2D shapes. A 2D shape is a flat closed shape that almost always has sides and vertices. What are sides and vertices? Sides are the straight lines that form a shape, like all of these sides here. Vertices are the corners where two straight lines meet, like all of these corners here. If we talk about one corner, we call it a vertex. If we talk about more than one corner, we call them vertices. Knowing the number of sides and vertices a shape has can help you to identify shapes, or classify them into shape families! For example, this square has four sides and four vertices. A quadrilateral, like this square, always has four sides and four vertices! Now we have learned about sides and vertices, let’s look at some different shapes. Here is a trapezoid. How many sides does it have? There are four sides. How many vertices does it have? There are four vertices. A trapezoid always has four sides and four vertices, which also makes it a part of the quadrilateral family. You might notice there are different shapes that share the same number of sides and vertices. Next we have a pentagon. How many sides and vertices does a pentagon have? There are five sides and five vertices! A pentagon always has five sides and five vertices. Some shapes are an exception to the rule that all 2D shapes have sides and vertices. One of them is this shape, which is a circle! What do you notice about the sides and vertices of this circle? There are zero sides and zero vertices. A circle will never have any sides or vertices.
While Nico continues to play the Shape Mayhem game, let’s review! Remember, a 2D shape almost always has sides and vertices. Sides are the straight lines that form a shape. Vertices are the corners where two straight lines meet. Some shapes are an exception to the rule that all 2D shapes have sides and vertices, and one of them is a circle. «Huh?» «I think that’s enough game time for today, Nico!» «Oh, you’re right! Let’s do something else now!» «You were right Nia! Playing outside is much more fun!
Sides and Vertices of Shapes exercise
Would you like to apply the knowledge you’ve learned? You can review and practice it with the tasks for the video Sides and Vertices of Shapes.

What are sides and vertices?
Hints
This shape has 3 sides. They are marked with light blue here.
This shape has 3 vertices. Each vertex is shown in dark blue here.
Solution
The square has 4 sides (the straight lines that form the shape) and 4 vertices (the points where the sides meet).

Where are the vertices?
Hints
There are seven vertices to find in total.
The vertices are the points where the straight sides meet.
There are three vertices in the triangle, and four vertices in the trapezoid.
Solution
Here are the vertices that are on the shapes on Nico’s game.

Investigating 2D shapes.
Hints
Remember that a circle is the only shape with zero sides and zero vertices.
Count how many sides the shape has. These are the straight lines that form the shape.
The vertices are the point where two straight sides meet.
Solution
 The circle has no vertices or sides.
 The triangle has 3 sides and 3 vertices.
 The square has 4 vertices and 4 sides.
 The pentagon has 5 vertices and 5 sides.

Quadrilaterals.
Hints
Remember that all quadrilaterals have four sides and four vertices.
Only 2D shapes (flat) can be quadrilaterals.
Solution
All the 2D shapes that have 4 sides and 4 vertices are quadrilaterals.
These are: square, rectangle, parallelogram and trapezoid.

How many sides can you see?
Hints
Remember that a circle is the only 2D shape with zero sides and zero vertices.
The squares has four sides.
Solution
In total, there are 17 sides.
 1 circles = 0 sides
 3 triangles = 9 sides
 1 square = 4 sides
 1 trapezoid = 4 sides
0 + 9 + 4 + 4 = 17

What shape am I?
Hints
Remember that the sides are the straight lines that form the outside of a 2D shape.
Remember that vertices are where the two sides of a 2D shape meet.
This is a hexagon.
Solution
1) I am a 2D shape. I am special as I am the only 2D shape with 0 vertices and 0 sides. What am I? I am a circle.
2) I am a closed 3 sided shape. I also have 3 vertices. What am I? I am a triangle.
3) I am a hexagon. I have an equal number of sides and vertices. If you add together my sides and vertices it totals 12.
4) I am a closed shape with fewer sides than a pentagon and more than 3 vertices. What am I? I am a quadrilateral.
More videos for the topic
Basic Shape Attributes
Sides and Vertices of Shapes
In Front of and Behind and Next to
Comparing Special Quadrilaterals—Let’s Practice!
Sides and Vertices of 2D Shapes — Let’s Practice!
Company
 Our Team
 Prices
 Jobs
Platform
How it works
 Tutorial Videos
 Exercises
 Sofahero
 Worksheets
 Chat
 Interactive books
Help
 FAQ
 Give Us Feedback
Legal
 Terms & Conditions
 Right of Withdrawal
 Privacy Policy
 Contact Us
 Do Not Sell My Personal Information
Any questions? Contact us!
help@sofatutor. com

sofatutor.com

sofatutor.ch

sofatutor.at

sofatutor.com

sofatutor.co.uk
Any questions? Contact us!
2D Shapes — Name, Definition, Properties
Introduction
2D shapes are flat, twodimensional figures that are used in mathematics. They are the most basic shapes that can be used to construct a variety of other shapes. Some of the common examples of 2D shapes include circles, squares, triangles, rectangles, and hexagons. These shapes are also known as plane figures.
A circle is a round shape with no corners or edges. It is defined by a center point and a radius. Circles are used in many everyday objects such as clocks and wheels.
Fill Out the Form for Expert Academic Guidance!
Grade
—Class 6Class 7Class 8Class 9Class 10Class 11Class 12
Target Exam
JEENEETCBSE
+91
Preferred time slot for the call
—9 am10 am11 am12 pm1 pm2 pm3 pm4 pm5 pm6 pm7 pm8 pm9 pm10pm
Please indicate your interest
Live ClassesRecorded ClassesTest SeriesSelf Learning
Language
—EnglishHindiMarathiTamilTeluguMalayalam
Verify OTP Code (required)
I agree to the terms and conditions and privacy policy.
A square is a foursided, flat shape with four equal sides and four right angles. It is a very common shape and is used in many everyday objects such as tiles, books, and windows.
A triangle is a threesided shape with three straight sides. The sides of a triangle are not necessarily equal. Triangles are used in many everyday objects such as roofs and sailboats.
A rectangle is a foursided shape with two pairs of equal sides. The sides of a rectangle are not necessarily equal. Rectangles are used in many everyday objects such as boxes and doors.
A hexagon is a sixsided shape with six equal sides. The sides of a hexagon are all equal. Hexagons are used in many everyday objects such as honeycomb cells and soccer balls.
2D shapes are a fundamental part of mathematics and are used in everyday objects. They are essential for constructing more complex shapes and understanding the world around us.
Properties of 2D Shapes
There are three properties of twodimensional shapes:
 Area: The area of a shape is the measure of how much surface is covered by the shape. It is measured in square units.
 Perimeter: The perimeter of a shape is the measure of how much distance is covered by the shape’s boundary. It is measured in units of length.
 Shape: The shape of a shape is the outline or boundary of the shape.
What is 2D Shape?
A 2D shape is a twodimensional object that has length and width but no height. Some examples of 2D shapes are squares, rectangles, circles, and triangles.
2D vs 3D Shapes
There are two types of shapes: 2D and 3D. A 2D shape is flat, and a 3D shape has depth. An example of a 2D shape is a square, and an example of a 3D shape is a cube.
Discovery of 2D shapes
 A triangle is a threesided polygon.
 A square is a foursided polygon with all sides equal in length.
 A rectangle is a foursided polygon with two parallel sides of equal length.
 A rhombus is a foursided polygon with all sides equal in length, but not all angles are equal.
 A parallelogram is a foursided polygon with two parallel sides and two opposite sides that are equal in length.
Two Dimensional Shapes in A Coordinate System.
There are three types of two dimensional shapes in a coordinate system: points, lines, and planes. Points are the simplest type of shape and are represented by a single coordinate. Lines are represented by two coordinate points and planes are represented by three coordinate points.
2D Shapes Names
 2dimensional shapes are a fundamental part of mathematics. A 2dimensional shape is simply a shape that has length and width, but no depth. There are a variety of different 2dimensional shapes, and we use specific names to identify them.
 The most basic 2dimensional shape is the point. A point is a shape with no width or length, just depth. Points are used in mathematics to represent positions in space.
 The next most basic 2dimensional shape is the line. A line is a shape with length, but no width. Lines are used to measure distances between points.
 The next most basic 2dimensional shape is the plane. A plane is a shape with both length and width. Planes are used to represent flat surfaces in space.
 There are a variety of other 2dimensional shapes, including rectangles, squares, circles, and ellipses. Each of these shapes has specific properties that distinguish them from one another. For example, rectangles have four right angles, squares have four equal sides, circles have a curved surface, and ellipses have two different radii.
 Being able to identify and name different 2dimensional shapes is an important part of mathematics. It enables us to communicate our ideas and thoughts effectively, and it helps us to better understand the world around us.
Curved Shapes
There are two types of curved shapes:
1. Closed curves: These are curves that have a beginning and an end.
2. Open curves: These are curves that don’t have a beginning or an end.
1) Circle
the correct word.
A. The moon orbits the Earth.
A. The Earth orbits the moon.
B. The moon rotates around the Earth.
B. The Earth rotates around the moon.
2) Ellipse
(3) Rectangle
(4) Triangle
(5) Trapezoid
(6) Square
Polygons
A polygon is a closed figure with straight sides. It is created by drawing line segments between two points, called the vertices, and then connecting the endpoints of the line segments.
1) Triangle (3 sides)
2) Rectangle (4 sides)
3) Square (4 sides)
4) Circle
2) Quadrilateral (4 sides)
3) Rectangle (4 sides, all right angles)
4) Square (4 sides, all right angles)
a) Square
b) Rectangle
c) Triangle
d) Circle
b) Rectangle
The area of a rectangle is found by multiplying the length by the width.
A = l × w
A = 120 × 20
A = 2400
3) Pentagon (5 sides)
4) Triangle (3 sides)
5) Square (4 sides)
4) Hexagon (6 sides)
A hexagon is a sixsided polygon.
5) Heptagon (7sides)
A heptagon is a sevensided polygon.
4) Octagon (8 sides)
5) Hexagon (6 sides)
6) Square (4 sides)
7) Triangle (3 sides)
8) Pentagon (5 sides)
9) Rhombus (4 sides, equal length)
Related content
Right Angle – Definition, Formula, Examples, and FAQs 
Geometric Shapes – Explanation with Examples and List of Geometric Shapes 
Compound Interest – Definition, Formula, Calculation, Methods & Solved Examples 
1 Billion in Rupees – Conversion, Solved Examples and FAQs 
Extra Questions for Class 9 Maths with Solutions Chapter Wise 
Class 12 Math NCERT Solutions – NCERT Solutions for Class 12 Maths 
Introduction To 3D Geometry, Coordinate System and Formulas 
NCERT Solutions For Class 6 Maths Data Handling Exercise 9.3 
Inequalities theorem Of Triangle 
Semicircle – Introduction, Formula, Properties, Solved Examples & FAQs 
we construct a service for experiments with shape reconstructions / Sudo Null IT News
Hello, Khabrovites! Today we want to share with you our experience in creating a service for testing 3D reconstruction models. In the notes we will:

briefly discuss what a 2Dto3D problem is,

take a look at the most successful algorithms and work,

compare the parametric and nonparametric approach s to restore the shape of the face and body of a person,

Let’s analyze how our service works for testing spatial reconstruction models.
Anyone who would like to move the girl from the cover of a glossy magazine to his room, at least in AR, in the manner of “ Miracles of Science ”, please under the cat =).
Note from the partner of the MAI IT Center and the organizer of the master’s program «VR/AR & AI» — the company PHYGITALISM.
2Dto3D task
Fig. 1 Comparison of various 2Dto3D architectures from [1]: the number at the bottom of each 3D model is mIoU with Ground truth.
In short: the 2dto3d task contains the essence of the problem in its name — we have 2D data (this can be one or many images of the object, a video in which the object is filmed from different angles, a sketch of the object’s outline and other similar data) and we want the machine learning algorithm to restore the 3D geometry in one form or another from this image or from the object class label.
There are similar tasks in which the 3D shape of objects is also restored, but the algorithms have a little more information at the input: for example, it can be not just an RGB image, but RGBD (that is, by a sparse point cloud).
Fig. 2 Voxlets architecture [2] restores spatial information for one RGBD image: a — original RGB image; b is a voxel model obtained using the depth of the source image layer; c is the real spatial model of objects; d is a spatial model obtained using Voxlets.
Of the review papers published in recent years, in which there are comparisons and discussions of different approaches to this problem, it is worth highlighting “ What do singleview 3d reconstruction networks learn? ” [ 1 ], in which the authors proposed their own algorithms for reconstructing the polygonal mesh of an object from a single image and compared it with other SOTA models of 2019. By the way, the task that will be considered below just belongs to the same narrower class of tasks Singleview 3D reconstruction .
Of the general points in this task, it is worth noting that the existing approaches are based on:0003
different forms of 3D representation (some approaches use voxels, some meshes, and some even parametric representation)
different error functions.
You can read about the types of representation learning in the already classic article “ Representation learning: A review and new perspectives ” [ 3 ]. Various forms of representation of 3D data and various loss functions for we covered in our notes here ( times and two times ). It is also worth mentioning that on paperswithcode there is a separate page dedicated to this very task.
Example architectures for 3D Reconstruction
Let’s take a look at some of the most wellknown 2Dto3D architectures as an example. Conventionally, it is possible to divide all architectures according to features:

final 3D representation (mesh, point cloud, voxels, etc. ),

parametric or nonparametric model,

general purpose model or adapted to specific object classes.
1. Mesh RCNN [2019/Facebook research] [4]
In this paper, researchers from Facebook AI Research use Mask RCNN [5] (there are many good review materials about this architecture, in Russian, for example, see this note ) to highlight object masks in images. After that, based on these masks, a voxel mesh of the future model is generated, and at the last stage, the vertices of the voxels are transformed using graph convolutions and the model becomes polygonal. It is worth noting a reasonable approach to the choice of the error function and regularizers.
Fig.4 Diagram of the Mesh RCNN device.
On the GitHub page of the project, Collab is available, in which you can test the model on your images.
Fig. 5 An example of using Mesh RCNN on our data. From left to right: original image, mask from Mask RCNN, reconstructed mesh.
2. Occupancy networks [2019] [6]
In this model, the probability that a given point in space belongs to the inside of an object is used as a form of representation of 3D objects:
knowledge of normals to optimize the mesh).
The second advantage is that the neural network is very compact due to the small and fixed number of input parameters.
It is worth noting that due to the fact that the network essentially approximates some probability function that describes the form and the way the input information for this form is encoded — \x can be arbitrary. This approach allows solving a variety of problems from the 3D ML field, which was demonstrated by the authors.
3. Atlas [2020][7]
Fig. 7 Animation showing the operation of Atlas Net (top) and network architecture (bottom).
This work, although not related to Singleview 3D reconstruction, is an interesting example of using another 3D representation — TSDF (truncated signed distance field / voxel space grid with the probability of a surface point in each voxel). In this approach, a TSDF is generated on each frame by the projection method, and then TSDF from all frames are aggregated and the final TSDF is obtained along with class labels for each voxel based on class labels in 2D images.
A feature of this work is the versatility of objects to which architecture can be applied and the fact that it can be used to restore not only the geometry of single objects, but also entire areas of space.
Restoring the geometry of the human body
Let’s single out the models that are adapted for restoring the geometry of the human body in general or the face in particular. First, consider parametric models.
We have already considered the parametric model of the human face surface in a note about differential rendering of , which used the classic model obtained at the Max Planck Institute back in 1999. Let’s consider more recent models based on the same parametric principle, which can be briefly expressed as follows:
«The geometry of a certain surface is represented by a parametric family of surfaces, which, for each fixed value of the parameter, is fixed in an admissible configuration. »
1. DECA (2018)[ 9 ]
This model uses FLAME to represent the geometry of a human face. In addition to geometry and textures, the model can also set a certain pose or expression according to the model (some alternative version of the Deep Fake model is obtained). Due to the fact that the basic geometry of the averaged face is already embedded in FLAME, the evaluation of irregularities and fine details by the network allows you to get a more detailed and less noisy surface.
Fig.8 An example of DECA operation on our image: from left to right — the original, initially found key points, key point adjustment, restored base geometry, geometry with texture map adjustment, textured mesh, restored depth map.
2. HMR (2018)[ 8 ]
Parametric model of the human body with estimated key points. The model is based on minimizing the deviation of pairs of key points, which makes it possible to train it without a 3D dataset. The video above is a demonstration of applying the model to the video we selected for the tests.
The disadvantages of parametric models include the inability to restore any details other than the basic geometry of the face or body (clothing, accessories, objects in hands, etc.).
3. PiFU HD (Facebook AI Research/2020)[ 11 ]
This nonparametric human body reconstruction and texture model from researchers at Facebook AI Research is an improvement on their previous work PiFU [ 10 9 0024].
The main idea of the first version of the architecture is that for an image, a spatial probability field of the probability of belonging to a given point inside the body is predicted (+ a similar network predicts the appearance of color on the body from a projection from a pixel). After obtaining such a probability field, on its basis by method marching cubes a mesh is built and painted based on the probability texture map.
Fig. 9 Architecture of the original PiFU [10].
In the new model, the geometry restoration is divided into two levels: global geometry (body shape) and local geometry (fine details), due to which it turns out to restore a more detailed mesh.
Designing our web service for 2Dto3D models
Pic. 10 An example of the interface of our service in a mobile browser.
Suppose you are a researcher who wants to test a large number of models, or a developer who needs to create a simple 2Dto3D model testing service, how would you do it? We also faced such a task, and we chose the path of data pipeline processing, where each stage was a separate Docker container, and for visualization and interaction with the service — a web client written in JS. Let’s go through to our 2Dto3D service and see how it works.
Fig. 11 2dto3d service architecture — server side and web interface.
The client interacts with the service through a browser on his device. At the same time, the frontend is written in JS and is made minimalistically in the form of a single screen for selecting a 2Dto3D model and its parameters, loading data (in this example, for the PiFU HD model, this will be a photograph of a person). The server is implemented in Python and runs inside a Docker container. After the server accepts data from the user, it will store them in the data store and in the appropriate queue RabbitMQ (which also runs in a separate Docker container) will send the job to the 2Dto3D service for processing.
Fig.12 2Dto3D service architecture — the main part related to data processing. Dotted blocks are functional.
First (although this is not necessary for all models), the image must be cropped and only the part where the person is present is left (get a crop and select a mask). To do this, you can wrap any of your favorite modern computer vision frameworks in a Docker container, we used gluoncv . The data obtained after preprocessing is also placed in the storage along with the original data.
After image preprocessing, the task for reconstruction goes to the geometry restoration algorithm (in our case, PiFU HD). We have modified the authors’ source code to fit into our pipeline and have optimized memory and performance. Since the implementation of many 3D ML algorithms requires calculations on a video card, this module is implemented as an nvidiadocker container.
After receiving 3D models, we save them in .glb format and then use the features of displaying models in AR in the browser (we additionally convert models to .usdz so that iOS devices can also work with models, there are restrictions).
In the future, it will be easy to replace or add modules to such a pipeline in order to work with many different architectures and share your experiments with the world (which is what we generally try to do). We hope you liked the idea of teaching machines to “sculpt” sculptures from an image. We will be glad if you share your ideas where such models can be applied in practice.
An example of placement in AR of the reconstructed model.
Sources:

Tatarchenko M. et al. What do singleview 3d reconstruction networks learn? //Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. — 2019. — S. 34053414. [ paper ]

Firman, Michael and Mac Aodha, Oisin and Julier, Simon and Brostow, Gabriel J. (2016). Structured Prediction of Unobserved Voxels From a Single Depth Image / Firman CVPR 2016 [ code ]

Bengio Y., Courville A., Vincent P. Representation learning: A review and new perspectives //IEEE transactions on pattern analysis and machine intelligence. — 2013. — T. 35. — No. 8. — S. 17981828. [ paper ]

Gkioxari G., Malik J., Johnson J. Mesh rcnn //Proceedings of the IEEE/CVF International Conference on Computer Vision. — 2019. — S. 97859795. [ paper ][ code ]

Kaiming He, Georgia Gkioxari, Piotr Dollar, Ross Girshick, “Mask RCNN.” arXiv:1409.4842 20172018 [ paper ][ code ]

Mescheder L. et al. Occupancy networks: Learning 3d reconstruction in function space //Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. — 2019. — S. 44604470. [ paper ][ code ]

Murez Z. et al. Atlas: Endtoend 3d scene reconstruction from posed images //arXiv preprint arXiv:2003.10432. – 2020. [ project page ]

Kanazawa A. et al. Endtoend recovery of human shape and pose //Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. — 2018. — S. 71227131. [ project page ]

Feng Y. et al. Learning an Animatable Detailed 3D Face Model from InTheWild Images //arXiv preprint arXiv:2012.04012. – 2020. [ paper ][ code ]

Saito S. et al. Pifu: Pixelaligned implicit function for highresolution clothed human digitization //Proceedings of the IEEE/CVF International Conference on Computer Vision. – 2019. — S. 23042314. [ project page ]

Saito S. et al. Pifuhd: Multilevel pixelaligned implicit function for highresolution 3d human digitization //Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. — 2020. — S. 8493. [ project page ]
Moving in 2D space — Godot Engine Documentation (stable) in Russian
Introduction
Every beginner asks the question: «How can I move my character?». Depending on your playstyle, you may have special requirements, but in general, movement in most 2D games is based on a small number of different ways.
For our examples, we will use KinematicBody2D, but these principles also apply to other types of nodes (Area2D, RigidBody2D).
Setting
Each of the examples below uses the same scene settings. Start by adding KinematicBody2D
with two children: Sprite
and CollisionShape2D
. You can use the Godot icon («icon.png») as a sprite texture or use any other 2D image available.
Open Project >
Project Settings and select the Action List tab. Add the following (for InputEvent reference):
8way traffic
In this example, we want the player to use four keys to select movement in a given direction (arrow keys: up/left/down/right or W/A/S/D). The term 8position move comes from the fact that a player can move diagonally by holding two keys at the same time.
Add a script to «KinematicBody2D» and then add the following code:
extends KinematicBody2D export (int) var speed = 200 var velocity = Vector2() func get_input(): velocity = Vector2() if Input.is_action_pressed("right"): velocity.x += 1 if Input.is_action_pressed("left"): velocity.x = 1 if Input.is_action_pressed("down"): velocity.y += 1 if Input.is_action_pressed("up"): velocity.y = 1 velocity = velocity.normalized() * speed func_physics_process(delta): get_input() velocity = move_and_slide(velocity)
In the function get_input()
we get four keypress events and add them to the direction vector. This approach allows you to cancel the simultaneous pressing of keys in opposite directions, but as a result, when adding diagonal movements, movement along the diagonal will be faster.
We can prevent this by applying a normalization ( normalize ) to the direction vector, so the length of the vector ( length ) becomes 1
, and then multiply it by the desired speed.
Advice
If you’ve never used vector algebra before, or want to refresh your memory, you can check out the vector algebra application in Godot Vector Math.
Note
If the code above doesn’t do anything when you press the keys, check the input action settings again as described in the Customizing part of this lesson.
Rotation + movement
This movement style is sometimes referred to as «Asteroid Style» because it looks like a classic arcade game. Pressing left/right rotates the character, up/down moves it forward or backward in the direction of the character.
extends KinematicBody2D export (int) var speed = 200 export (float) var rotation_speed = 1.5 var velocity = Vector2() var rotation_dir = 0 func get_input(): rotation_dir = 0 velocity = Vector2() if Input. is_action_pressed("right"): rotation_dir += 1 if Input.is_action_pressed("left"): rotation_dir = 1 if Input.is_action_pressed("down"): velocity = Vector2(speed, 0).rotated(rotation) if Input.is_action_pressed("up"): velocity = Vector2(speed, 0).rotated(rotation) func_physics_process(delta): get_input() rotation += rotation_dir * rotation_speed * delta velocity = move_and_slide(velocity)
Here we have added two new variables to keep track of the direction of rotation and the speed of rotation. As before, pressing two opposite keys at the same time cancels the rotation. The rotation is done by changing the property rotation
.
To set the speed, we use the «Vector2.rotated()« method so that the speed is in the direction of the body. rotated()
is a useful vector function that can be used in many circumstances where trigonometric functions would otherwise have to be used.
Rotate + move with mouse
This movement style is a variation of the previous one. Now the direction is set by moving the mouse instead of the keyboard. Thanks to the «look at» function, the character will always look at the mouse cursor. Forward/backward movements remain the same.
extends KinematicBody2D export (int) var speed = 200 var velocity = Vector2() func get_input(): look_at(get_global_mouse_position()) velocity = Vector2() if Input.is_action_pressed("down"): velocity = Vector2(speed, 0).rotated(rotation) if Input.is_action_pressed("up"): velocity = Vector2(speed, 0).rotated(rotation) func_physics_process(delta): get_input() velocity = move_and_slide(velocity)
We are using the Node2D «look_at()« method to indicate the direction of the player. Without this function, we can achieve the same effect by setting the angle as described below:
rotation = get_global_mouse_position().angle_to_point(position)
Click and move
In the last example, only the mouse is used to move the character. Tapping on the screen will make the player move in the indicated direction.
extends KinematicBody2D export (int) var speed = 200 onready var target = position var velocity = Vector2() func_input(event): if event.is_action_pressed("click"): target = get_global_mouse_position() func_physics_process(delta): velocity = position.direction_to(target) * speed # look_at(target) if position.distance_to(target) > 5: velocity = move_and_slide(velocity)
Notice the «distance_to()« check we do before moving. Without this test, the body may begin to tremble when trying to reach a given position, as it may overshoot it when moving and try to return back by overshooting it again.
Uncommenting the line «look_at()« will cause the body to turn in the direction it is moving.
Hint
This technique can also be used as the basis for a «tracking» character. The target position can be any object in the direction you want to move.