基本上,我希望一个物体坐在地面上时都能跳跃。我这里有3个脚本,1个用于初始化值,2个用于FixedUpdate方法,3个用于对撞脚本。我希望我的对象跳到屏幕高度的1/4,然后跳到1 / 2、3 / 4 ..,依此类推。但这似乎不起作用。我在Unity文档中使用的公式是Impulse =质量x距离/时间。我想我的物体第一次跳到接近屏幕高度的1/4,第二次跳到接近屏幕一半的高度。但是第3和第4个物体的高度过高,以致物体刚离开屏幕。我也知道球对象的XY坐标,分别是其高度和宽度的一半。
//script #1
public static bool AllowJump = false;
float ScreenHeight = (float)(Camera.main.orthographicSize * 2.0);
public static int jumpCount = 0;
GameObject ball = new GameObject();
ball.AddComponent<RigidBody2D>();
ball.GetComponent<RigidBody2D>().mass = 1f;
ball.GetComponent<RigidBody2D>().gravityScale = 1f;
//more initial values here...my ball is set XY coordinates (0, (1/2 of
//screenheight - half of ball's height) * -1
//impulse = mass * distance / time
public static float ballVelocity = ball.GetComponent<RigidBody2D>().mass
* (ScreenHeight * .25f) / 1f;
//distance is 1/4 of the screen, time 1 sec
//script #2
void FixedUpdate()
{
if(AllowJump)
{
ball.GetComponent<RigidBody2D>().AddForce(ball.transform.up *
ballVelocity * jumpCount, ForceMode2D.Impulse);
AllowJump = false;
}
}
//sript #3 collision script that is attached to my GameObject ball
void OnCollisionStay2D(Collision2D c)
{
//if the ball is sitting on the ground
jumpCount++;
AllowJump = true;
}