This is the 23rd day of my participation in the August More Text Challenge.More challenges in August

I’ve written a couple of small game blogs in Unity before, and I feel good about it, so I’m going to keep writing. Today’s angry Birds primer.

Angry Birds used to be a popular game around the world, where birds shoot pigs with springs. The pig is protected by all sorts of things. The rules of the game are relatively simple.

Same old rule. Renderings first

The scene is relatively simple, the background picture is blue, and various objects are placed in the middle. In fact, objects have been arranged manually in the early stage, so there is not much to say in this. Go straight to the topic and look at the code.

public float forceNeeded = 1000; float collisionForce(Collision2D coll) { // Estimate a collision's force (speed * mass) float speed = coll.relativeVelocity.sqrMagnitude; if (coll.collider.GetComponent<Rigidbody2D>()) return speed * coll.collider.GetComponent<Rigidbody2D>().mass; return speed; } void OnCollisionEnter2D(Collision2D coll) { if (collisionForce(coll) >= forceNeeded) Destroy(gameObject); }}Copy the code

The above part of the code is hanging on the pig’s body, in fact, the collision force is greater than the predetermined value, so as to let the pig destroy. To Destroy(gameObject) is to Destroy the pig. Pigs have no additional logic code.

 public GameObject effect;

    void OnCollisionEnter2D(Collision2D coll) {
        // Spawn Effect, then remove Script
        Instantiate(effect, transform.position, Quaternion.identity);
        Destroy(this);
    }
Copy the code

This is the script of the ice. There’s not a lot of logic in there.


 void OnMouseUp() {
        // Disable isKinematic
        GetComponent<Rigidbody2D>().isKinematic = false;
        
        // Add the Force
        Vector2 dir = startPos - (Vector2)transform.position;
        GetComponent<Rigidbody2D>().AddForce(dir * force);

        // Remove the Script (not the gameObject)
        Destroy(this);
    }

    void OnMouseDrag() {        
        // Convert mouse position to world position
        Vector2 p = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        // Keep it in a certain radius
        float radius = 1.8f;
        Vector2 dir = p - startPos;
        if (dir.sqrMagnitude > radius)
            dir = dir.normalized * radius;

        // Set the Position
        transform.position = startPos + dir;
    }
Copy the code

The whole code, probably the most important part, this is the function of the fork. This includes dragging under mouse click and then releasing the mouse button. Drag function with record mouse position, drag the position of the bird. Then the mouse release function to calculate the direction of the launch and add a force to the bird process.

This is a relatively basic simple game example, interested in learning Unity, you can pay attention to the public number: poetic code, message to me, I teach you systematic learning.