【发布时间】:2020-08-07 22:37:54
【问题描述】:
每个人。我是 Unity 2D 和 C# 的新手,我想知道如何阻止我的车在我的游戏中滑行和向前滑动,因为如果我不希望它这样做,因为如果它滑得太厉害了。我希望这样,如果我不给汽车任何输入,或者给汽车几乎立即停止或开始向另一方向移动的计数器输入。我尝试过创建 Physics2D 材质并增加摩擦力,但它确实对游戏玩法没有影响。我也尝试过检查,如果没有玩家输入,则 rb.velocity 设置为 0,或当前值的 0.2 左右,因此它是一个更平滑的停止,但只有在玩家移动然后放开移动键,如果他们尝试向相反的方向移动,则不会。我还考虑过通过将先前位置与当前位置进行比较来检查汽车的移动方向,然后向相反方向增加力以停止汽车,但这似乎非常耗费性能,我真的不知道我会去哪里开始。如果有人对我将如何做这件事有任何建议,请告诉我如何做。这是我到目前为止的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
public Rigidbody2D carRigidbody;
public Rigidbody2D backTire;
public Rigidbody2D frontTire;
private float movement;
public float fspeed = 100;
public float bspeed = 60;
public float carTorque = 10;
public float decVel = .9f;
private bool beganMoving;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal");
}
void FixedUpdate() {
if (movement == 1 || movement == -1) {
beganMoving = true;
}
if (movement == 0 && beganMoving) {
backTire.velocity = new Vector2 (backTire.velocity.x * decVel * Time.fixedDeltaTime, backTire.velocity.y);
frontTire.velocity = new Vector2 (backTire.velocity.x * decVel * Time.fixedDeltaTime, backTire.velocity.y);
}
backTire.AddTorque(-movement * bspeed * Time.fixedDeltaTime);
frontTire.AddTorque(-movement * fspeed * Time.fixedDeltaTime);
carRigidbody.AddTorque(-movement * carTorque * Time.fixedDeltaTime);
}
}
【问题讨论】:
标签: c# unity3d game-physics