The jump is written entirely in accordance with the idea of moving in the direction, and it is found that the object moves to the control in an instant.
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
// If you don't add Space.World, if the object rotates, the direction of the jump is not up, it is inclined
transform.Translate(new Vector3(0, 10, 0), Space.World);
}
}
If using MovePosition
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
var component = transform.GetComponent<Rigidbody2D>();
component.MovePosition(component.position + new Vector2(0, 5));
}
}
Slow ascent, highly available controls, a bit more code
private float speed = 30;
bool jump = false;
float jhigh = 0f;
float maxJhigh = 5f;
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
jump = true;
print("start");
jhigh = 0;
}
if (jump) {
float high = 1 * speed * Time.deltaTime;
if (jhigh + high >= maxJhigh) {
jump = false;
}
transform.Translate(new Vector3(0, high, 0), Space.World);
jhigh += high;
print(jhigh);
}
}
Use Force to apply force, there is a sense of bouncing, this is recommended
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
var component = transform.GetComponent<Rigidbody2D>();
component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
}
Added ray detection, you can only jump on the ground
//for output on the screen
private void OnDrawGizmos() {
Gizmos.color = Color.white;
Gizmos.DrawRay(transform.position + colliderOffset,Vector3.left);
}
void Update() {
RaycastHit2D onGround2 = Physics2D.Raycast(transform.position + colliderOffset, -Vector2.up);
print("b" + transform.position + ",c=" + colliderOffset + ",d=" + onGround2.distance);
if (onGround2.distance <= 0) {
if (Input.GetKeyDown(KeyCode.Space)) {
var component = transform.GetComponent<Rigidbody2D>();
component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
}
}
The problem with the last version is that it may not be on the ground, but it needs to be filtered on other hidden colliders
Debug.DrawRay(transform.position + colliderOffset, Vector3.down * 5);
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)) {
RaycastHit2D onGround2 = Physics2D.Raycast(transform.position + colliderOffset, -Vector2.up, 5, buildingsMask);
if (onGround2.collider != null && onGround2.distance <= 0) {
component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
}
}
second stage jump
/**
* whether to skip once
*/
private bool jumpOne;
void jump() {
Debug.DrawRay(transform.position + colliderOffset, Vector3.down * 5);
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)) {
RaycastHit2D onGround2 = Physics2D.Raycast(transform.position + colliderOffset, -Vector2.up, 5, buildingsMask);
if (onGround2.collider != null && onGround2.distance <= 0) {
rig.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
jumpOne = true;
}
else if (jumpOne) {
// second jump
rig.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
jumpOne = false;
}
}
}
Thank you hope it can help you