【发布时间】:2015-11-03 16:10:46
【问题描述】:
我是 Unity 的新手,我正在尝试在经典 2D 地图(超级马里奥之类)上移动一个简单的方块。
我用addForce跳转,按计划进行。
但现在,我正在尝试水平移动我的角色。
首先,我尝试使用tramsform.translation(),我很快注意到这不是正确的方法,因为这种方法会“传送”角色,如果它移动得太快,它可以传送到墙后面。我也尝试使用addForce,但我希望我的角色具有恒定的速度,并且它会产生惯性,所以当我释放键时它不会立即停止。我也尝试使用.MovePosition(),但使用这种方法时角色会颤抖(显然,由于重力)。
那么,水平移动角色(Rigidbody2D)的正确方法是什么?
这是我尝试不同的代码:
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);
}
}
}
【问题讨论】:
-
您可能会研究角色控制器脚本——它们旨在模仿刚体等物理行为,同时还支持倾向于产生角色移动的自定义逻辑。