65 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			65 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
using System.Collections;
 | 
						|
using System.Collections.Generic;
 | 
						|
using UnityEngine;
 | 
						|
 | 
						|
public class AppleTree : MonoBehaviour
 | 
						|
{
 | 
						|
    [Header("Set in Inspector")]
 | 
						|
    // Prefab for instantiating apples
 | 
						|
    public GameObject applePrefab;
 | 
						|
    public GameObject rottenApplePrefab;
 | 
						|
    // Speed at which the AppleTree moves
 | 
						|
    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;
 | 
						|
    // Rate at which RottenApples will be instantiated
 | 
						|
    public float secondsBetweenRottenAppleDrops = 3f;
 | 
						|
    // Start is called before the first frame update
 | 
						|
    void Start()
 | 
						|
    {
 | 
						|
        // Dropping apples every second
 | 
						|
        Invoke("DropApple", 2f);
 | 
						|
        // Dropping rotten apples every 3 seconds
 | 
						|
        Invoke("DropRottenApple", 2f);
 | 
						|
    }
 | 
						|
 | 
						|
    void DropApple() {
 | 
						|
        GameObject apple = Instantiate<GameObject>(applePrefab);
 | 
						|
        apple.transform.position = transform.position;
 | 
						|
        Invoke("DropApple", secondsBetweenAppleDrops);
 | 
						|
    }
 | 
						|
 | 
						|
    void DropRottenApple() {
 | 
						|
        GameObject rottenApple = Instantiate<GameObject>(rottenApplePrefab);
 | 
						|
        rottenApple.transform.position = transform.position;
 | 
						|
        Invoke("DropRottenApple", secondsBetweenRottenAppleDrops);
 | 
						|
    }
 | 
						|
 | 
						|
    // Update is called once per frame
 | 
						|
    void Update()
 | 
						|
    {
 | 
						|
        // Basic Movement
 | 
						|
        Vector3 pos = transform.position;
 | 
						|
        pos.x += speed * Time.deltaTime;
 | 
						|
        transform.position = pos;
 | 
						|
        // Changing Direction
 | 
						|
        if (pos.x < -leftAndRightEdge) {
 | 
						|
            speed = Mathf.Abs(speed);
 | 
						|
        } else if (pos.x > leftAndRightEdge) {
 | 
						|
            speed = -Mathf.Abs(speed);
 | 
						|
        } 
 | 
						|
    }
 | 
						|
 | 
						|
    // Update exactly 50 times per second
 | 
						|
    void FixedUpdate() 
 | 
						|
    {
 | 
						|
        if (Random.value < chanceToChangeDirections) {
 | 
						|
            speed *= -1;
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |