似乎没有任何效果,玩了几个小时,复制并粘贴了解决方案'来自谷歌但没有 更改maxSpeed变量不会做任何事情。物体仍然像巴里艾伦一样飞过屏幕。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Range (0, 5)]public int speed;
public Rigidbody2D rb2D;
public Vector3 veloc;
public float maxSpeed;
void Start ()
{
rb2D = GetComponent<Rigidbody2D> ();
speed = 4;
maxSpeed = 0.01f;
veloc = GetComponent <Rigidbody2D>().velocity;
}
void Update ()
{
if(Input.GetKey(KeyCode.W))
{
rb2D.AddForce (Vector3.up * speed);
}
if(Input.GetKey(KeyCode.S))
{
rb2D.AddForce (-Vector3.up * speed);
}
if(Input.GetKey(KeyCode.D))
{
rb2D.AddForce (Vector3.right * speed);
}
if(Input.GetKey(KeyCode.A))
{
rb2D.AddForce (-Vector3.right * speed);
}
}
void FixedUpdate ()
{
if(veloc.magnitude > maxSpeed)
{
rb2D.velocity = rb2D.velocity.normalized * maxSpeed;
}
}
}
答案 0 :(得分:1)
我需要多睡一觉。如果遇到类似问题,只需将Fixedoc.magnitude更改为FixedUpdate方法中的rb2D.velocity.magnitude。该对象确实“口吃”。达到最大速度但我还没有找到解决方案。
void Start ()
{
rb2D = GetComponent<Rigidbody2D> ();
speed = 4;
maxSpeed = 0.01f;
}
void Update ()
{
if(Input.GetKey(KeyCode.W))
{
rb2D.AddForce (Vector3.up * speed);
}
if(Input.GetKey(KeyCode.S))
{
rb2D.AddForce (-Vector3.up * speed);
}
if(Input.GetKey(KeyCode.D))
{
rb2D.AddForce (Vector3.right * speed);
}
if(Input.GetKey(KeyCode.A))
{
rb2D.AddForce (-Vector3.right * speed);
}
}
void FixedUpdate ()
{
if(rb2D.velocity.magnitude > maxSpeed)
{
rb2D.velocity = rb2D.velocity.normalized * maxSpeed;
}
}
}
答案 1 :(得分:0)
仅此:
void Update() {
rb2D.velocity = Vector3.ClampMagnitude(rb2D.velocity, maxSpeed);
}