c# - How to stop my character going off-screen?
问题描述
I want my character to stop everytime I hit the edge of the screen/canvas, so I added some rectangle at the end of each border(with a 2d collider), so my character will collide with it and stop moving in that direction, but the thing is that if, for example, I hit the left rectangle and I still press A to move left, my character strarts 'shaking'. I tried to solve that by setting the speed of it to 0 when it hits the certain rectangle, but then I cant move at all in any directions after I get to the edge.
public class CharacterMovement : MonoBehaviour {
public float speed = 5f;
void Start() {
}
void Update() {
if (Input.GetKey(KeyCode.W))
{
transform.Translate(0, speed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(0, -speed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "offscreen")
{
speed = 0f;
}else
{
speed = 5f;
}
}
}
解决方案
我不熟悉单声道行为方法,但我认为问题在于当你等于边缘时,它在下一次更新中保持不变。由于没有任何东西使它成为错误,因此速度保持为 0。
尝试在您的更新方法中检查每个按下的键。
就像是
if (key ==moveleft)
{
if(sprite.leftedge>edgeoftheleftscreen+1)
Sprite.moveleft();
}
if(key==moveright)
{
if(sprite.rightedge<edgeoftherightscreen-1)
Sprite.moveright();
}
希望这可以帮助。
推荐阅读
- java - Java:按下 html 按钮在两个 Http Servlet 之间发送数据
- crystal-lang - Crystal 不为联合做自动推断类型?
- git - 如何删除本地位置不存在但仍存在于原始位置的文件?
- reactjs - 在 React 中的多个上下文提供者之间传递数据
- mysql - 将复选框值从 jTable 保存到数据库中
- c# - Selenium:使用序列选择具有相似属性的元素
- javascript - 在 JavaScript 中计算不包括周末和联邦假日的前一个工作日
- c - 如何正确使用 strsep() 解析数组?
- json - 来自 json 文件的 Ansible 列表
- javascript - 仅在大型反应项目中渲染特定组件