use*_*504 11 c# physics unity-game-engine
有没有人在团结的2D游戏中有一个好的跳跃剧本?我的代码有效,但仍然远没有跳跃,看起来它正在飞行.
using UnityEngine;
using System.Collections;
public class movingplayer : MonoBehaviour {
public Vector2 speed = new Vector2(10,10);
private Vector2 movement = new Vector2(1,1);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis ("Horizontal");
float inputY = Input.GetAxis ("Vertical");
movement = new Vector2(
speed.x * inputX,
speed.y * inputY);
if (Input.GetKeyDown ("space")){
transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
}
}
void FixedUpdate()
{
// 5 - Move the game object
rigidbody2D.velocity = movement;
//rigidbody2D.AddForce(movement);
}
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*ama 26
通常用于跳跃的人使用Rigidbody2D.AddForce同Forcemode.Impulse.看起来您的物体在Y轴上被推动一次,并且由于重力会自动下降.
例:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
Run Code Online (Sandbox Code Playgroud)
las*_*lar 11
上面的答案现在已经过时使用Unity 5或更新版本.改用它!
GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);
Run Code Online (Sandbox Code Playgroud)
我还想补充一点,这使得跳跃高度超级私密,只能在脚本中编辑,所以这就是我所做的......
public float playerSpeed; //allows us to be able to change speed in Unity
public Vector2 jumpHeight;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f); //makes player run
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) //makes player jump
{
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
Run Code Online (Sandbox Code Playgroud)
这使得它可以在Unity中编辑跳转高度,而无需返回脚本.
旁注 - 我想评论上面的答案,但我不能,因为我是新来的.:)