当前位置:网站首页>Unity beginner 1 - character movement control (2D)
Unity beginner 1 - character movement control (2D)
2022-07-29 07:57:00 【Lin Fusheng】
This article comes from learning chutianbo Teacher's notes , link b standing
stay unity The role of China Mobile generally adopts the control role transtion Attribute position The coordinate axis on which it is based , Generally, it's a quadratic equation xy Axis
The simplest move
public class RubyController : MonoBehaviour
{
// Once per frame Update
// Move the game object to the right every frame 0.1
void Update()
{
// Create a Vector2 object position, Used to get the location of the current object
Vector2 position = transform.position;
// change position Of x Coordinate value , Let it add 0.05
position.x = position.x + 0.05f;
// Update the location of the current object to the new location
transform.position = position;
}
}
So every frame our character will show x The positive axis of moves 0.05 distance ( The higher the number of frames , The faster you move ).
Move with control
public class RubyController : MonoBehaviour
{
// Once per frame Update
// Move the game object to the right every frame 0.1
void Update()
{
// Get horizontal input , Press left , Will get -1.0 f ; Press right , Will get 1.0 f
float horizontal = Input.GetAxis("Horizontal");
// Get vertical input , Press down , Will get -1.0 f ; Press up , Will get 1.0 f
float vertical = Input.GetAxis("Vertical");
// Get the current location of the object
Vector2 position = transform.position;
// modify location
position.x = position.x + 0.1f * horizontal;
position.y = position.y + 0.1f * vertical;
// New location for game object
transform.position = position;
}
}
This seems to be used unity Move the built-in components , By getting the default vertical keys and horizontal cases , That is, it directly corresponds to wasd And direction keys .
The second way to control movement
public class RubyController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 position = transform.position;
if (Input.GetKey("w"))
{
position.y = position.y + 0.05f;
}else if (Input.GetKey("a"))
{
position.x = position.x - 0.05f;
}else if (Input.GetKey("s"))
{
position.y = position.y - 0.05f;
}
else if(Input.GetKey("d")){
position.x = position.x +0.05f;
}
transform.position = position;
}
}
Use getkey Customize the control method
But the one used in the first and second GetKey and GetAxis The difference between the two methods is this .GetKey Only 0 and 1 The difference between , No existence 0.5 perhaps 0.05. however getAxis It's a smooth curve ( Mobile control recommendation ).
Use it directly update Disadvantages of mobile
because update Is directly linked to the number of game frames , That is, one call per frame update, So the higher your frame number , The faster the character moves
Suppose the game 30 frame , that 0.1f Moving in one second is 0.1*30 by 3 A unit of . If it is 60 frame , One second is 6 A unit of .
The first method to solve the problem that the number of frames affects the moving rate : Lock frame
void Start()
{
// Turn on vertical synchronization //
QualitySettings.vSyncCount = 0;
// Frame rate set to 50//
Application.targetFrameRate = 50;
}
But locking frames will reduce the quality of the game picture , So we use unit seconds to control Ruby Action of
The temporary final solution
public class RubyController : MonoBehaviour
{
public float speed = 0.1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.x = position.x + speed * horizontal * Time.deltaTime;
position.y = position.y + speed * vertical * Time.deltaTime;
transform.position = position;
}
}
In this case , We will find that speed=5 Only when you use frame control 0.1 The speed of ;
Solve the problem of collision bug
If you control the movement according to the last code above , Then we will find that when two rigid bodies collide , There will be ghosts in our characters , That is, our position first enters the position occupied by the collision body , Then it bounced out , So here we need to introduce the rigid body components of the object to solve
void Start()
{
// Get the rigid body component of the current game object
rigidbody2d = GetComponent<Rigidbody2D>();
}
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
}
// Fixed interval refresh method
private void FixedUpdate()
{
Vector2 position = transform.position;
position.x = position.x + speed * horizontal * Time.deltaTime;
position.y = position.y + speed * vertical * Time.deltaTime;
rigidbody2d.position = position;
}
Here we need to put the acquisition mobile in update in , Because it's called every frame , It will be smoother , Put it in FixedUpdate Is about 20ms One call .
good , The conventional bug Time
After the above set of movements using physical systems , We will join the enemy's movement later , After colliding with other powerful objects , Our protagonist will also get the force in the moving direction of another object ( It's about the robot walking down , The protagonist is collided under the robot , The protagonist will go down until he meets another collider )
According to the solution, rigid body movement cannot directly use position assignment
therefore rigidbody2d.position = position; We should change this sentence into rigidbody2d.MovePosition(position);
This article is only a personal preliminary study unity used
link : Ruby’s Adventure:2D beginner
link : What is vertical synchronization
link :Time.deltaTime Official documents of
边栏推荐
- C language data type
- Pat class a 1150 traveling salesman problem
- Technology sharing | quick intercom integrated dispatching system
- C# 之 volatile关键字解析
- Zero technology is deeply involved in the development of privacy computing financial scenario standards of the ICT Institute
- How to connect VMware virtual machine to external network under physical machine win10 system
- Shell script - global variables, local variables, environment variables
- 在js中,0表示false,非0表示true
- Very practical shell and shellcheck
- Popular cow G
猜你喜欢

Measured waveform of boot capacitor short circuit and open circuit of buck circuit

Dynamic thresholds buffer management in a shared buffer packet switch paper summary

207. Curriculum

C language data type

Research on autojs wechat: the final product of wechat automatic information sending robot (effective demonstration)
![[deep learning] data preparation -pytorch custom image segmentation data set loading](/img/7d/61be445febc140027b5d9d16db8d2e.png)
[deep learning] data preparation -pytorch custom image segmentation data set loading

Technology sharing | quick intercom integrated dispatching system

LANDSCAPE
功能自动化测试实施的原则以及方法有哪些?

The smallest positive number that a subset of an array cannot accumulate
随机推荐
Solving linear programming problems based on MATLAB
[note] the art of research - (tell a good story and argument)
Strongly connected component
Android interview question | how to write a good and fast log library?
[lecture notes] how to do in-depth learning in poor data?
Sqlmap(SQL注入自动化工具)
下推分析的限制
MySQL 45 讲 | 07 行锁功过:怎么减少行锁对性能的影响?
Data unit: bit, byte, word, word length
[cryptography experiment] 0x00 install NTL Library
QT connects two qslite databases and reports an error qsqlquery:: exec: database not open
Technology sharing | quick intercom integrated dispatching system
Day 014 2D array exercise
Cs61abc sharing session (VI) detailed explanation of program input and output - standard input and output, file, device, EOF, command line parameters
黑盒测试常见错误类型说明及解决方法有哪些?
NLP introduction + practice: Chapter 5: using the API in pytorch to realize linear regression
As long as flutter is data, it will be judged null
LANDSCAPE
Jiamusi Market Supervision Bureau carried out special food safety network training on epidemic and insect prevention
技术分享| 快对讲综合调度系统