c# - Changing the player's position in Update() or FixedUpdate() method?
问题描述
In my game I've a case that when the player is touching the collider of a specific GameObject and the player press the X key I want to change his position to the position of another GameObject.
To do that I use the following code
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.X))
{
// Check Colliders collition
// End of Check Colliders collition
var playerRigidBody = GetComponent<Rigidbody2D>();
playerRigidBody.position = AnotherObject.transform.position;
}
}
I've realized that very often when I press the X key the player don't change his position to the position of the other GameObject. However if I move the code to the Update() method it works as expected (with no delay).
But I've read in the official documentation and in a lot of blogs that the code related to physics and Rigidbodies must be put in the FixedUpdate instead of Update
So the question is the following:
For this case putting the code in the Update() method is not recommended? (Note that I'm not using forces nor torques)
If it's not recommended then how can I assure that every time the player press the X key he will change his position to the other GameObject position in FixedUpdate()?
解决方案
In general if you want a smooth movement you should rather use MovePosition
in FixedUpdate
otherwise everything regarding Physics (so also RigidBody) you should always do in FixedUpdate
(as explained in the API there as well).
You should however catch the GetKeyDown
in Update
and split those two things:
bool wasClicked;
RigidBody playerRigidBody;
void Start()
{
// do this only once!
playerRigidBody = GetComponent<Rigidbody2D>();
}
void Update()
{
// Catch user input here
if (Input.GetKeyDown(KeyCode.X))
{
wasClicked = true;
}
}
void FixedUpdate()
{
// Handle physics here
if(!wasClicked) return;
playerRigidBody.position = AnotherObject.transform.position;
wasClicked = false;
}
推荐阅读
- python - AADSTS50011:请求中指定的回复 URL 与为应用程序配置的回复 URL 不匹配。如何指定重定向 URI?
- angular - 角度引导日期选择器输入通过单击添加样式
- arrays - Django检查数组内的数组并更改模板
- c++ - 驻留在 std:tuple 中的对象中元素的复杂求和
- facebook-graph-api - 如何深入了解 Instagram 的帖子?
- ios - 将 Swift 协议一致性添加到 Objective-C 标头并使其公开
- questdb - 在 QuestDB 导入中使用用户定义的模式手动设置时间戳格式
- c - 在 MacOS 中无法接收 GRE 数据包
- solr - SOLR 搜索,日光浴室 PHP - 了解评分
- ios - 如何在collectionview Swift中调整第二个单元格的大小?