Three scripts to be attached to an AppleTree, Apple, and a Basket to catch randomly falling objects.

using UnityEngine;
using System.Collections;

public class AppleTree : MonoBehaviour {

	// Prefab for instantiating apples
	public GameObject applePrefab;

	// Spped at which the AppleTree moves in meters/second
	public float speed = 1f;

	// Distance where AppleTree turns around
	public float leftAndRightEdge = 10f;

	// Chance that the AppleTree will change directions
	public float chanceToChangeDirections = 0.1f;

	// Rate at which Apples will be instantiated
	public float secondsBetweenAppleDrops = 1f;


	// Use this for initialization
	void Start () {

		// Dropping apples every second
		InvokeRepeating("DropApple", 2f, secondsBetweenAppleDrops);		// InvokeRepeating calls the DropApple function after a 2 sec. delay, then drop based on secondsBetweenAppleDrops variable.
	}

	void DropApple (){
		GameObject apple = Instantiate (applePrefab) as GameObject;		// Defines the DropApple function, which creates a new instance of the Apple prefab as a new GameObject
		apple.transform.position = transform.position;
	}
	
	// Update is called once per frame
	void Update () {

		// Basic Movement
		Vector3 pos = transform.position; 	// Creates a new Vector variable named pos and sets it to the current position
		pos.x += speed * Time.deltaTime; 	// Increase the X componenet of pos by the speed times Time.deltaTime, a time-based measure to run the game independent of framerate
		transform.position = pos;			// reassign the modified pos back to transform.position


		// Changing Direction

		if (pos.x < -leftAndRightEdge) {
			speed = Mathf.Abs (speed);								// Move right
		} else if ( pos.x > leftAndRightEdge ) {
			speed = -Mathf.Abs (speed); 							// Move left
		}
	}

	void FixedUpdate () {
		if ( Random.value < chanceToChangeDirections ) {		// Random.value returns a random numb. between 0 and 1.
			speed *= -1; 											// Change directions if random.value is less than chanceToChangeDirection
		}

	}


}
<!- Save this file as Apple.cs and attach it to a sphere with an attached Physics component
 -->

using UnityEngine;
using System.Collections;

public class Apple : MonoBehaviour {

	public static float bottomY = -10f;				// Creates a new float var. that is STATIC, 
													// meaning every instance of Apples on the screen will have the same value for bottomY

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (transform.position.y < bottomY) {		// If any instance of Apple is less than the value of bottomY,
			Destroy (this.gameObject);				// destroy this instance of the Apple GameObject
		}
	
	}
}

 

Tagged on:     

Leave a Reply