我不確定天氣或不使用 Time.deltaTime 我認為實施它會很好,但我不確定如何實施,我已經嘗試過,但我搞砸了
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float horSpeed;
[SerializeField] private float vertSpeed;
private Rigidbody2D rb;
private bool isJumping;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// we store the initial velocity, which is a struct.
var v = rb.velocity;
if (Input.GetKey(KeyCode.Space) && !isJumping)
{
v.y = vertSpeed * Time.deltaTime;
isJumping = true;
}
if (Input.GetKey(KeyCode.A))
v.x = -horSpeed * Time.deltaTime;
if (Input.GetKey(KeyCode.D))
v.x = horSpeed * Time.deltaTime;
if (Input.GetKey(KeyCode.S))
v.y = -vertSpeed * Time.deltaTime;
rb.velocity = v;
if(Input.GetKey(KeyCode.Escape))
SceneManager.LoadScene(0);
}
private void OnCollisionEnter2D(Collision2D collision)
{
isJumping = false;
}
}
當我嘗試添加它時,我的角色移動得非常慢
uj5u.com熱心網友回復:
增加 vertSpeed 和 horSpeed 的速度,或者你可以使用 rb.AddForce()
uj5u.com熱心網友回復:
將輸入向量與 Time.DeltaTime 相乘使其與幀速率無關。
uj5u.com熱心網友回復:
試試我的代碼。它沒有跳躍,需要剛體和 collider2D。我將其用于 2d RPG 游戲。
public float speed = 2f;
private Rigidbody2D rb;
private Vector2 moveDelta;
//Inputs
private float x;
private float y;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
//Reset V3
x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
moveDelta = new Vector2(x, y);
//Facing Toward Mouse
float dir = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized.x;
//Rigidbody
rb.velocity = moveDelta * speed * Time.fixedDeltaTime;
//Swap side of the sprite
if(dir > 0)
{
transform.localScale = Vector3.one;
}else if (dir < 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/523511.html
標籤:C#unity3d二维
下一篇:為什么不先分配變數就不能更改值?
