c# - Unity - 像声波一样运行循环而不会摔倒
问题描述
我正在为一个自由职业者制作这个 2D 平台游戏,我必须做一个声音机制,我必须让角色通过一个完整的循环而不摔倒,我意识到要这样做首先我必须旋转角色符合他穿过循环,但第二部分是我卡住的地方。
所以,基本上,我怎样才能让角色在不摔倒的情况下循环运行。
private void OnCollisionEnter2D(Collision2D coll)
{
Vector3 collRotation = coll.transform.rotation.eulerAngles;
if (coll.gameObject.tag == "Ground")
{
//in this part i rotate the player as he runs through the loop
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, collRotation.z);
//this is the part that i am stuck, trying to figure out how to make the character stay in the loop without falling, i tried collision detection,
//i tried raycasting but nothing seems to work
if (IsGrounded)
{
GetComponent<Rigidbody2D>().AddForce(Vector2.down, ForceMode2D.Impulse);
}
}
}
解决方案
最常用于重制和类似的技巧是在进入时获得玩家角色的速度。
// Feel free to adjust this to whatever works for your project.
const float minimumAttachSpeed = 2f;
// This should be your characters current movement speed
float currentSpeed;
// You need a Rigidbody in this example, or you can just disable
// any custom gravity solution you may have created
Rigidbody2D rb;
如果角色的速度超过了最低附着速度,那么您可以让他们以该速度遵循预定义的路径。
bool LoopAttachmentCheck()
{
return minimumAttachSpeed <= currentSpeed;
}
现在您可以检查自己是否移动得足够快!我假设在这个例子中你使用的是Rigidbody2D ...
(此检查仅应在您进入或当前在循环中时运行)
void Update()
{
if( LoopAttachmentCheck() )
{
// We enable this to prevent the character from falling
rb.isKinematic = true;
// Here you write the code that allows the character to move
// in a circle, e.g. via a bezier curve, at the currentSpeed.
}
else
{
rb.isKinematic = false;
}
}
由您来实现实际的旋转行为。如果我是你,一个很好的方法是(假设它是一个完美的圆)从圆的中心使用RotateAround。
如果您有更复杂的形状,您可以使用航路点进行移动,并以您的速度遍历它们。
一旦你跟不上速度,你的角色就会掉下来(例如,如果玩家决定停止跑步)并且 Rigibody2D 将变得运动。
希望这可以帮助!
推荐阅读
- r - 将 data.frame 中的值添加到另一个 data.frame 中匹配两个条件的新列
- node.js - 使用nodejs sequelize中指定的字段隐藏数据库列表中的一个结果
- r - R 检查警告:需要孤立包
- python - pymysql 不在 python cgi 中运行
- javascript - 如何删除 Twitter 关注者计数按钮上的 .com 或扩展名?
- python - 斯科特是谁?- Seaborn pairplot 中的 ValueError:无法将字符串转换为浮点数:'scott'
- python - 带有队列的 Python 3.8 websocket echo 客户端:asyncio.Queue get() 不会动态添加队列项
- winforms - 如何使用 powershell 和 WPF 构建动态链接列表?
- java - Java 在运行时添加类路径
- python - pyqt5 中的嵌入式绘图显示在任务栏中,但单击时不会显示