3. Instantiation

The first thing we must do is give the projectile some forward movement so it can zip across the scene when it’s launched by the player.

1.Make the projectile fly forwards

using UnityEngine;

public class Pizza_gun : MonoBehaviour
{
    public GameObject Ammo;

    public float Weapon_Bullet_Projectile_Speed = 60.0f;
    // Start is called before the first frame update
    void Start()
    {
        Ammo = GetComponent<GameObject>();
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector3.forward * Time.deltaTime * Weapon_Bullet_Projectile_Speed);
    }
}

using UnityEngine;

public class Movement : MonoBehaviour
{
    [SerializeField]
    private float speed = 10.0f;
    [SerializeField]
    private float xRange = 10.0f;
    [SerializeField]
    private float horizontalInput;
    [SerializeField] 
    public GameObject ProjectilePrefab;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {


        horizontalInput = Input.GetAxis("Horizontal");
        // Calculate the desired position based on the input
        Vector3 desiredPosition = transform.position + Vector3.right * -horizontalInput * Time.deltaTime * speed;
        // Clamp the desired position within the x range
        float clampedX = Mathf.Clamp(desiredPosition.x, -xRange, xRange);
        desiredPosition = new Vector3(clampedX, desiredPosition.y, desiredPosition.z);
        // Move the object to the clamped position
        transform.position = desiredPosition;
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // shoot pizza
            Instantiate(ProjectilePrefab, transform.position, ProjectilePrefab.transform.rotation);
        }
    }
}

5.Make animals into prefabs

6.Destroy projectiles offscreen

7. Destroy animals offscreen

8.Lesson Recap

New Functionality
  • The player can press the Spacebar to launch a projectile prefab,

Projectile and Animals are removed from the scene if they leave the screen

New Concepts & Skills
  • Create Prefabs
  • Override Prefabs
  • Test for Key presses
  • Instantiate objects
  • Destroy objects
  • Else-if statements

Next Lesson

(

Lesson 2.2 - Food Flight
Skills practiced:
Absolute Beginner Code Comprehension
Interpret simple code
Improve simple code using the features of an IDE
Absolute Beginner Application Scripting
Use common logic structures to control the execution of code.
Write code that utilizes the various Unity APIs
Implement appropriate data types
Write code that integrates into an existing system
Implement a code style that is efficient and easy to read
Prototype new concepts
)


Revision #2
Created 21 May 2023 00:44:25 by naruzkurai
Updated 18 June 2023 09:54:37 by naruzkurai