跳轉功能的除錯日志正確顯示在控制臺中,但我找不到任何方法來撰寫代碼,當我按下按鈕時,實際上使角色在 Y 軸上向上移動。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KittenController : MonoBehaviour
{
Rigidbody2D rigidbody2d;
Animator animator;
public float speed;
public float jumpForce;
private float idleTimer;
float horizontal;
float vertical;
//int direction;
Vector2 lookDirection = new Vector2(1, 0);
Vector2 jumping = new Vector2(0, 100);
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
idleTimer = 0;
}
void Update()
{
horizontal = Input.GetAxis("Horizontal");
// vertical = Input.GetAxis("Vertical");
Vector2 move = new Vector2(horizontal, vertical);
// Jump Movement
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
Debug.Log("Space Pressed");
// animator.SetTrigger("Jump");
}
if (move.magnitude == 0)
{
idleTimer = Time.deltaTime;
//Debug.Log("Idle Time is : " idleTimer);
}
else
{
idleTimer = 0;
}
if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
{
lookDirection.Set(move.x, move.y);
lookDirection.Normalize();
//Debug.Log("X is: " lookDirection);
}
//animator.SetFloat("Look X", lookDirection.x);
animator.SetFloat("Move X", lookDirection.x);
animator.SetFloat("Speed", move.magnitude);
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
position.x = position.x speed * horizontal * Time.deltaTime;
position.y = position.y speed * vertical * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
void Jump()
{
//rigidbody2d.AddForce(jumping, ForceMode2D.Impulse);
//rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x, jumpForce);
rigidbody2d.velocity = Vector2.up * jumpForce;
Debug.Log("Jumping");
}
}
uj5u.com熱心網友回復:
你也許跳,但rightafter,幾乎在同一時間,你要設定的y位置與rigidbody2d.MovePosition(position);在FixedUpdate()
如果特定需要恒定增量時間(物理或重放系統),請首先不要使用固定更新。你應該使用Update()代替。
其次,通常使用代碼和物理(設定剛體的速度)來處理移動設定變換并不是一個好主意。您需要選擇您的物件是隨物理移動還是transform.position在代碼中設定(可能也應用物理,但由您自己編碼)。考慮到如果您transform.position直接在代碼中設定 a ,如果物件隨物理移動,則物理計算很可能沒有意義,因此會出現意外結果。
我會洗掉FixedUpadte()和大部分代碼中的所有代碼,并嘗試確定跳轉是否有效,無論是使用rigidbody2d.velocity = Vector2.up * jumpForce;還是使用rigidbody2d.AddForce(new Vector2(0f, 1.0f), ForceMode2D.Impulse). 我會嘗試分開計算運動,也許用rigidbody2d.AddForce(new Vector2(1.0f, 0f), ForceMode2D.Force). 然后,也許嘗試針對各自的輸入一起解決它們。
如果你想直接處理位置設定transform.position而不是使用物理,我也會把問題分成更小的問題,首先實作運動也許
position.x = position.x speed * horizontal * Time.deltaTime;
然后是跳躍。因為position.y您可以應用勻加速運動物理并將該邏輯應用到您跳躍時的垂直位置,或者用您定義的運動來計算您自己的跳躍型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347451.html
