Skip to content

Instantly share code, notes, and snippets.

@ultimateprogramer
Created July 7, 2017 09:51
Show Gist options
  • Select an option

  • Save ultimateprogramer/61a705a973d67411cb167a9a948d1837 to your computer and use it in GitHub Desktop.

Select an option

Save ultimateprogramer/61a705a973d67411cb167a9a948d1837 to your computer and use it in GitHub Desktop.
Unity3D Code Snippets of Interest from AngryBirdsClone
public float Health = 70f;
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.GetComponent<Rigidbody2D>() == null) return;
float damage = col.gameObject.GetComponent<Rigidbody2D>().velocity.magnitude * 10;
//don't play audio for small damages
if (damage >= 10)
GetComponent<AudioSource>().Play();
//decrease health according to magnitude of the object that hit us
Health -= damage;
//if health is 0, destroy the block
if (Health <= 0) Destroy(this.gameObject);
}
// This is attached to the Main Camera Object
void Start()
{
Camera camera = GetComponent<Camera>();
float aspect = Mathf.Round(camera.aspect * 100f) / 100f;
//this is to be altered different Windows Phone 8 aspect ratios
//there should be a better way of doing this
if (aspect == 0.6f) //WXGA or WVGA
camera.orthographicSize = 5;
else if (aspect == 0.56f) //720p
{
camera.orthographicSize = 4.6f;
}
}
[HideInInspector]
public Vector3 StartingPosition;
private const float minCameraX = 0;
private const float maxCameraX = 13;
[HideInInspector]
public bool IsFollowing;
[HideInInspector]
public Transform BirdToFollow;
// Use this for initialization
void Start()
{
StartingPosition = transform.position;
}
// Update is called once per frame
void Update()
{
if (IsFollowing)
{
if (BirdToFollow != null) //bird will be destroyed if it goes out of the scene
{
var birdPosition = BirdToFollow.transform.position;
float x = Mathf.Clamp(birdPosition.x, minCameraX, maxCameraX);
//camera follows bird's x position
transform.position = new Vector3(x, StartingPosition.y, StartingPosition.z);
}
else
IsFollowing = false;
}
}
void OnTriggerEnter2D(Collider2D col)
{
//destroyers are located in the borders of the screen
//if something collides with them, the'll destroy it
string tag = col.gameObject.tag;
if(tag == "Bird" || tag == "Pig" || tag == "Brick")
{
Destroy(col.gameObject);
}
}
Camera camera;
Vector3 previousCameraTransform;
public float ParallaxFactor;
camera = Camera.main;
previousCameraTransform = camera.transform.position;
void Start()
{
CurrentGameState = GameState.Start;
slingshot.enabled = false;
//find all relevant game objects
Bricks = new List<GameObject>(GameObject.FindGameObjectsWithTag("Brick"));
Birds = new List<GameObject>(GameObject.FindGameObjectsWithTag("Bird"));
Pigs = new List<GameObject>(GameObject.FindGameObjectsWithTag("Pig"));
//unsubscribe and resubscribe from the event
//this ensures that we subscribe only once
slingshot.BirdThrown -= Slingshot_BirdThrown; slingshot.BirdThrown += Slingshot_BirdThrown;
}
Vector3 previousCameraTransform;
void Update () {
Vector3 delta = camera.transform.position - previousCameraTransform;
delta.y = 0; delta.z = 0;
transform.position += delta / ParallaxFactor;
previousCameraTransform = camera.transform.position;
}
public float Health = 150f;
public Sprite SpriteShownWhenHurt;
private float ChangeSpriteHealth;
// Use this for initialization
void Start()
{
ChangeSpriteHealth = Health - 30f;
}
// Collision with a Collider2D
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.GetComponent<Rigidbody2D>() == null) return;
//if we are hit by a bird
if (col.gameObject.tag == "Bird")
{
GetComponent<AudioSource>().Play();
Destroy(gameObject);
}
else //we're hit by something else
{
//calculate the damage via the hit object velocity
float damage = col.gameObject.GetComponent<Rigidbody2D>().velocity.magnitude * 10;
Health -= damage;
//don't play sound for small damage
if (damage >= 10)
GetComponent<AudioSource>().Play();
if (Health < ChangeSpriteHealth)
{
//change the shown sprite
GetComponent<SpriteRenderer>().sprite = SpriteShownWhenHurt;
}
if (Health <= 0) Destroy(this.gameObject);
}
}
[HideInInspector]
//the bird to throw
public GameObject BirdToThrow;
//a vector that points in the middle between left and right parts of the slingshot
private Vector3 SlingshotMiddleVector;
private void ThrowBird(float distance)
{
//get velocity
Vector3 velocity = SlingshotMiddleVector - BirdToThrow.transform.position;
BirdToThrow.GetComponent<Bird>().OnThrow(); //make the bird aware of it
//old and alternative way
//BirdToThrow.GetComponent<Rigidbody2D>().AddForce
// (new Vector2(v2.x, v2.y) * ThrowSpeed * distance * 300 * Time.deltaTime);
//set the velocity
BirdToThrow.GetComponent<Rigidbody2D>().velocity = new Vector2(velocity.x, velocity.y) * ThrowSpeed * distance;
//notify interested parties that the bird was thrown
if (BirdThrown != null)
BirdThrown(this, EventArgs.Empty);
}
//the left and right parts of the slingshot
public Transform LeftSlingshotOrigin, RightSlingshotOrigin;
//two line renderers to simulate the "strings" of the slingshot
public LineRenderer SlingshotLineRenderer1;
public LineRenderer SlingshotLineRenderer2;
// Use this for initialization
void Start()
{
//set the sorting layer name for the line renderers
//for the slingshot renderers this did not work so I
//set the z on the background sprites to 10
//hope there's a better way around that!
SlingshotLineRenderer1.sortingLayerName = "Foreground";
SlingshotLineRenderer2.sortingLayerName = "Foreground";
TrajectoryLineRenderer.sortingLayerName = "Foreground";
slingshotState = SlingshotState.Idle;
SlingshotLineRenderer1.SetPosition(0, LeftSlingshotOrigin.position);
SlingshotLineRenderer2.SetPosition(0, RightSlingshotOrigin.position);
//pointing at the middle position of the two vectors
SlingshotMiddleVector = new Vector3((LeftSlingshotOrigin.position.x + RightSlingshotOrigin.position.x) / 2,
(LeftSlingshotOrigin.position.y + RightSlingshotOrigin.position.y) / 2, 0);
}
[HideInInspector]
//the bird to throw
public GameObject BirdToThrow;
//this linerenderer will draw the projected trajectory of the thrown bird
public LineRenderer TrajectoryLineRenderer;
void DisplayTrajectoryLineRenderer2(float distance)
{
SetTrajectoryLineRenderesActive(true);
Vector3 v2 = SlingshotMiddleVector - BirdToThrow.transform.position;
int segmentCount = 15;
float segmentScale = 2;
Vector2[] segments = new Vector2[segmentCount];
// The first line point is wherever the player's cannon, etc is
segments[0] = BirdToThrow.transform.position;
// The initial velocity
Vector2 segVelocity = new Vector2(v2.x, v2.y) * ThrowSpeed * distance;
float angle = Vector2.Angle(segVelocity, new Vector2(1, 0));
float time = segmentScale / segVelocity.magnitude;
for (int i = 1; i < segmentCount; i++)
{
//x axis: spaceX = initialSpaceX + velocityX * time
//y axis: spaceY = initialSpaceY + velocityY * time + 1/2 * accelerationY * time ^ 2
//both (vector) space = initialSpace + velocity * time + 1/2 * acceleration * time ^ 2
float time2 = i * Time.fixedDeltaTime * 5;
segments[i] = segments[0] + segVelocity * time2 + 0.5f * Physics2D.gravity * Mathf.Pow(time2, 2);
}
TrajectoryLineRenderer.SetVertexCount(segmentCount);
for (int i = 0; i < segmentCount; i++)
TrajectoryLineRenderer.SetPosition(i, segments[i]);
}
// Update is called once per frame
void Update()
{
switch (slingshotState)
{
case SlingshotState.Idle:
//fix bird's position
InitializeBird();
//display the slingshot "strings"
DisplaySlingshotLineRenderers();
if (Input.GetMouseButtonDown(0))
{
//get the point on screen user has tapped
Vector3 location = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//if user has tapped onto the bird
if (BirdToThrow.GetComponent<CircleCollider2D>() == Physics2D.OverlapPoint(location))
{
slingshotState = SlingshotState.UserPulling;
}
}
break;
case SlingshotState.UserPulling:
DisplaySlingshotLineRenderers();
if (Input.GetMouseButton(0))
{
//get where user is tapping
Vector3 location = Camera.main.ScreenToWorldPoint(Input.mousePosition);
location.z = 0;
//we will let the user pull the bird up to a maximum distance
if (Vector3.Distance(location, SlingshotMiddleVector) > 1.5f)
{
//basic vector maths :)
var maxPosition = (location - SlingshotMiddleVector).normalized * 1.5f + SlingshotMiddleVector;
BirdToThrow.transform.position = maxPosition;
}
else
{
BirdToThrow.transform.position = location;
}
float distance = Vector3.Distance(SlingshotMiddleVector, BirdToThrow.transform.position);
//display projected trajectory based on the distance
DisplayTrajectoryLineRenderer2(distance);
}
else//user has removed the tap
{
SetTrajectoryLineRenderesActive(false);
//throw the bird!!!
TimeSinceThrown = Time.time;
float distance = Vector3.Distance(SlingshotMiddleVector, BirdToThrow.transform.position);
if (distance > 1)
{
SetSlingshotLineRenderersActive(false);
slingshotState = SlingshotState.BirdFlying;
ThrowBird(distance);
}
else//not pulled long enough, so reinitiate it
{
//distance/10 was found with trial and error :)
//animate the bird to the wait position
BirdToThrow.transform.positionTo(distance / 10, //duration
BirdWaitPosition.transform.position). //final position
setOnCompleteHandler((x) =>
{
x.complete();
x.destroy();
InitializeBird();
});
}
}
break;
case SlingshotState.BirdFlying:
break;
default:
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment