官术网_书友最值得收藏!

Shooting a projectile

This is the stepping stone for scenarios where we want to have control over gravity-reliant objects, such as balls and grenades, so we can then predict the projectile's landing spot, or be able to effectively shoot a projectile at a given target.

Getting ready

This recipe differs slightly as it doesn't rely on the base AgentBehaviour class.

How to do it...

  1. Create the Projectile class along with its member variables to handle the physics:
    using UnityEngine;
    using System.Collections;
    
    public class Projectile : MonoBehaviour
    {
        private bool set = false;
        private Vector3 firePos;
        private Vector3 direction;
        private float speed;
        private float timeElapsed;
    }
  2. Define the Update function:
    void Update ()
    {
        if (!set)
            return;
        timeElapsed += Time.deltaTime;
        transform.position = firePos + direction * speed * timeElapsed;
        transform.position += Physics.gravity * (timeElapsed * timeElapsed) / 2.0f;
        // extra validation for cleaning the scene
        if (transform.position.y < -1.0f)
            Destroy(this.gameObject);// or set = false; and hide it
    }
  3. Finally, implement the Set function in order to fire the game object (for example, calling it after it is instantiated in the scene):
    public void Set (Vector3 firePos, Vector3 direction, float speed)
    {
        this.firePos = firePos;
        this.direction = direction.normalized;
        this.speed = speed;
        transform.position = firePos;
        set = true;
    }

How it works...

This behavior uses high-school physics in order to generate the parabolic movement.

There's more...

We could also take another approach: implementing public properties in the script or declaring member variables as public and, instead of calling the Set function, having the script disabled by default in the prefab and enabling it after all the properties have been set. That way, we could easily apply the object pool pattern.

See also

For further information on the object pool pattern, please refer to the following Wikipedia article and an official Unity Technologies video tutorial available online at the following addresses:

主站蜘蛛池模板: 铜陵市| 如皋市| 特克斯县| 苏州市| 福安市| 连平县| 宜君县| 孟津县| 郓城县| 大安市| 建瓯市| 平遥县| 萝北县| 大埔区| 买车| 黔江区| 马尔康县| 沙雅县| 阿坝县| 济阳县| 哈密市| 大悟县| 万全县| 左贡县| 如皋市| 桐梓县| 建湖县| 永宁县| 济源市| 台南市| 长丰县| 惠州市| 阳城县| 湘潭市| 白银市| 丰镇市| 法库县| 关岭| 灌云县| 太仆寺旗| 抚远县|