当前位置:网站首页>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
边栏推荐
- The new generation of public chain attacks the "Impossible Triangle"
- C language data type
- Limitations of push down analysis
- Analyze the roadmap of 25 major DFI protocols and predict the seven major trends in the future of DFI
- LANDSCAPE
- Sqlmap (SQL injection automation tool)
- Pytorch's skill record
- Ansible (automation software)
- mysql 使用 DATE_FORMAT(date,'%Y-%m')
- Output 1234 three digits without repetition
猜你喜欢
Do you want to meet all the needs of customers
An Optimal Buffer Management Scheme with Dynamic Thresholds论文总结
Sqlmap (SQL injection automation tool)
《nlp入门+实战:第五章:使用pytorch中的API实现线性回归》
RoBERTa:A Robustly Optimized BERT Pretraining Approach
Cs61abc sharing session (VI) detailed explanation of program input and output - standard input and output, file, device, EOF, command line parameters
Up sampling deconvolution operation
Mutationobserver document learning
功能自动化测试实施的原则以及方法有哪些?
[cryoelectron microscope | paper reading] a feature guided, focused 3D signal permutation method for subtogram averaging
随机推荐
webapi接口文件下载时跨域问题
CDM - code division multiplexing (easy to understand)
Sqlmap(SQL注入自动化工具)
Cfdiv1+2-bash and a high math puzzle- (gcd+ summary of segment tree single point interval maintenance)
My entrepreneurial neighbors
What is the use of chat robots? What type? After reading these, you will understand!
Do you want to meet all the needs of customers
LANDSCAPE
Volatile keyword parsing of C #
The beauty of do end usage
Limitations of push down analysis
Very practical shell and shellcheck
Why don't you like it? It's easy to send email in cicd
[untitled] format save
You study, I reward, 21 day learning challenge | waiting for you to fight
Zip gzip tar compression Advanced Edition
IonIcons图标大全
Access数据库引入datagridview数据后,显示错误
[freeze electron microscope] analysis of the source code of the subtomogram alignment function of relion4.0 (for self use)
Useful websites