Pitbulik GR
Pitbulik GR

Reputation: 11

Automatically jump script

I'm working on a 2D game (for smartphone) which is automatically jumping, and I want to give a player movement (accelerometer) (a similar principle as doodle jump). How to make automatically jumping of 2D sprite? I tried to create an animation but it will not move using the accelerometer. So I coded script for automatically jump but it's not working. any help? (automatically jump means when player hits ground, jump again)

public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
Rigidbody2D coll;

void Start(){
    coll = GetComponent<Rigidbody2D>();
}
void Update() {
    if (coll.gameObject.tag == "Ground") {
        moveDirection = Vector3.zero;
        moveDirection.x = 1;
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;

    }

}

}

So can someone give me script when player hit ground, player will jump? I want to move up and to the right.

Upvotes: 1

Views: 1827

Answers (1)

OsmanSenol
OsmanSenol

Reputation: 146

Player object should have collider2D and rigidbody2D. Ground object should have collider2D and "Ground" tag. This code must be on player object.

public int power;

void Update()
{
    transform.position = new Vector3(transform.position.x + Input.acceleration.x, transform.position.y, transform.position.z);
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.collider.gameObject.tag.Equals("Ground"))
    {
        rigidbody2D.AddForce(Vector2.up * power);
    }
}

I hope it works.

Upvotes: 1

Related Questions