我在Unity中非常新,我试图在经典的2D地图上移动一个简单的正方形(超级马里奥像)。Unity中的水平移动
我使用addForce
跳,它按计划进行。 但是现在,我试图水平移动我的角色。
首先,我试着用tramsform.translation()
,我很快注意到这不是正确的方法,导致这种方法“传送”角色,如果它移动得太快,它可以传送到墙后。我也尝试使用addForce
,但我希望我的角色具有恒定的速度,并且具有惯性,所以当我释放密钥时它不会立即停止。我也试着用.MovePosition()
,但人物正在用这种方法摇晃(显然,由于重力)。
那么,什么是适当的方式来移动角色(Rigidbody2D)horizontaly?
这里是我的代码与试不同:
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
private Rigidbody2D rb;
public Vector2 velocity;
public float jumpforce;
// Use this for initialization
void Start() {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update() {
Debug.Log(velocity);
if (Input.GetKeyDown("space")){
rb.AddForce(new Vector2(0, jumpforce), ForceMode2D.Impulse);
}
if (Input.GetKey("a")){ // move to the left
rb.AddForce(-velocity * Time.deltaTime, ForceMode2D.Impulse);
//rb.MovePosition(rb.position - velocity * Time.fixedDeltaTime);
//transform.Translate(-velocity);
}
if (Input.GetKey("d")){ // move to the right
rb.AddForce(velocity * Time.deltaTime, ForceMode2D.Impulse);
//rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
//transform.Translate(velocity);
}
}
}
您可能会研究角色控制器脚本 - 它们旨在模拟像刚体一样的物理行为,同时还支持倾向于提供角色移动的自定义逻辑。 – rutter