::武器を変える。

youtu.be/SlFWpbw6N3Q

>>改善すべき:武器変更を他のスクリプトに入れて使う?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestApp3 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // :: Initialise Buttons
        Button btnNoHand = GameObject.Find("Button_NoHand").GetComponent<Button>();   
        Button btnAxe = GameObject.Find("Button_Axe").GetComponent<Button>();   
        Button btnSpear = GameObject.Find("Button_Spear").GetComponent<Button>();

        // :: Create Character and Instantiate
        GameObject unit = Object.Instantiate(Resources.Load<GameObject>("ch_03_01"));

        // :: Initialise dummyRHand
        Transform dummyRHand = null;

        // :: Find DummyRHand and Remember it
        Transform[] unitChildren = unit.transform.GetComponentsInChildren<Transform>();
        foreach(var child in unitChildren)
        {
            if(child.name == "DummyRHand")
            {
                dummyRHand = child;
                break;
            }
        }

        // :: Initialise currentWeaponName
        string currentWeaponName = null;

        // :: Add Event Listener : Button No Hand
        btnNoHand.onClick.AddListener(() =>
        {
            // :: When you have weapon
            if(currentWeaponName != null)
            {
                // :: Find current weapon by name
                Transform currentWeapon = dummyRHand.transform.Find(currentWeaponName);

                // :: Release parent
                currentWeapon.transform.SetParent(null);

                // :: Destroy current weapon
                Object.Destroy(currentWeapon.gameObject);

                // :: Set Current Weapon Name : null
                currentWeaponName = null;
            }
        });

        // :: Add Event Listener : Button Axe
        btnAxe.onClick.AddListener(() =>
        {
            // :: When you don't have weapon
            if (currentWeaponName == null)
            {
                // :: Resources Load and Set Parent
                var currentWeapon = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Axe_3"));
                currentWeapon.transform.SetParent(dummyRHand, false);

                // :: Set Current Weapon Name
                currentWeaponName = currentWeapon.name;
            }
        });

        // :: Add Event Listener : Button Spear
        btnSpear.onClick.AddListener(() =>
        {
            // :: When you don't have weapon
            if (currentWeaponName == null)
            {
                // :: Resources Load and Set Parent
                var currentWeapon = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Spear_7"));
                currentWeapon.transform.SetParent(dummyRHand);
                currentWeapon.transform.localPosition = Vector3.zero;
                currentWeapon.transform.localRotation = Quaternion.Euler(Vector3.zero);

                // :: Set Current Weapon Name
                currentWeaponName = currentWeapon.name;
            }
        });

    }
}
블로그 이미지

RIsN

,

::目標たちを辿って宝箱を開けてみよう。

:2020-10-29

youtu.be/taYBOVJ_OHg

>>改善すべき:関数を分けるより、一つのログを作ってそれに従うようにしよう。

>>疑問点:キュー(Queue)を使ってみたが方向性が違った感じがする。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class App : MonoBehaviour
{
    // Start is called before the first frame update
    Queue<GameObject> targets;
    GameObject beforeTarget;
    GameObject chestClosed;
    GameObject chestOpened;
    GameObject lastTarget;
    void Start()
    {
        // :: Load Targets with name
        targets = new Queue<GameObject>();
        for(int i = 1; i <= 3; i++)
        {
            targets.Enqueue(GameObject.Find("Target" + i));

            if(i == 3)
            {
                lastTarget = GameObject.Find("Target" + i);
            }
        }
        Debug.Log(targets.Count);

        // :: Initialise Chest
        GameObject chestPrefabA = Resources.Load<GameObject>("chest_close");
        GameObject chectPrefabB = Resources.Load<GameObject>("chest_open");

        // :: Render Chest Closed and Set Position
        chestClosed = Object.Instantiate<GameObject>(chestPrefabA);
        chestClosed.transform.position = lastTarget.transform.position + new Vector3(0, 0f, 0.5f);
        chestClosed.transform.eulerAngles = new Vector3(-90, -90, 0);

        // :: Render Chest Open and Set Position and Set Active false;
        chestOpened = Object.Instantiate<GameObject>(chectPrefabB);
        chestOpened.transform.position = chestClosed.transform.position;
        chestOpened.transform.eulerAngles = chestClosed.transform.eulerAngles;
        chestOpened.SetActive(false);

        // :: Initialise beforeTarget
        beforeTarget = new GameObject();

        // :: Button Load and Attach OnClick Function : Create
        Button BUTTON_create = GameObject.Find("Button_Create").GetComponent<Button>();
        BUTTON_create.onClick.AddListener(() => OnClick());

        // :: Button Load and Attach OnClick Function : GoAndTurn
        Button BUTTON_goAndTurn = GameObject.Find("Button_GoAndTurn").GetComponent<Button>();
        BUTTON_goAndTurn.onClick.AddListener(() => { RunToTarget(); });
    }

    // :: Run to Target
    void RunToTarget(float speed = 0.5f)
    {   
        // :: If you have remain targets
        if(targets.Count > 0)
        {
            // :: Go Target
            beforeTarget = targets.Peek();
            unit.GetComponent<Unit>().RunToTarget(targets.Dequeue(), speed);
        }
    }
    // :: Go Target
    void WalkToTarget(float speed = 0.5f)
    {
        // :: If you have remain targets
        if (targets.Count > 0)
        {
            // :: Go Target
            beforeTarget = targets.Peek();
            unit.GetComponent<Unit>().WalkToTarget(targets.Dequeue(), speed);
        }
    }

    // :: Go Complete
    void GoComplete()
    {
        // :: Target Remains
        if(targets.Count > 0)
        {
            // :: When arrived target1
            if (targets.Peek().name.Contains("2"))
            {
                // :: Look at target forward
                unit.GetComponent<Unit>().LookTarget(beforeTarget.transform.forward);
                unit.GetComponent<Unit>().WaitNow();
            }
            else
            {
                // :: Walk To Target
                this.WalkToTarget();
            }
        } else
        {
            Debug.Log("You've got treasure!");
            chestClosed.SetActive(false);
            chestOpened.SetActive(true);
            
        }
    }

    // :: Wait Complete
    void WaitComplete()
    {
        Debug.Log("wait is Over!");

        // :: Walk To Target
        this.WalkToTarget();
    }

    // :: OnClick Function
    // ::: for Variables
    GameObject unit; // :: Unit
    void OnClick()
    {
        // :: Unit Resources Load & Instantiate
        unit = Instantiate<GameObject>(Resources.Load<GameObject>("ch_03_01"));
        unit.AddComponent<Unit>().goComplete = () => { GoComplete(); };
        unit.GetComponent<Unit>().waitComplete = () => { WaitComplete(); };
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Unit : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // :: Look at direction of Target
    public void LookTarget(Vector3 direction)
    {
        this.gameObject.transform.LookAt(direction);
    }

    // :: Go and Turn with Target
    // ::: for Variables

    // :: Run To Target Function
    // ::: for Variables
    bool isGo = false;
    string animationName_Run = "run@loop";
    string animationName_Idle = "idle@loop";
    GameObject target; // ::: target
    float speed = 0.5f; // ::: Move Speed
    public void RunToTarget(GameObject target, float speed = 0.5f)
    {
        // :: Remember Target
        this.target = target;

        // :: Remember Speed
        this.speed = speed;

        // :: Look at Target
        this.LookTarget(this.target.transform.position);

        // :: Animation Run
        this.gameObject.GetComponent<Animation>().Play(animationName_Run);

        // :: Start Update
        isGo = true;
    }

    // :: Walk To Target Function
    string animationName_Walk = "walk@loop";
    public void WalkToTarget(GameObject target, float speed = 0.05f)
    {
        // :: Remember Target
        this.target = target;

        // :: Remember Speed
        this.speed = speed;

        // :: Look at Target
        this.LookTarget(this.target.transform.position);

        // :: Animation Run
        this.gameObject.GetComponent<Animation>().Play(animationName_Walk);

        // :: Start Update
        isGo = true;
    }

    // :: Wait Function
    float waitTime;
    bool isWait = false;
    float elapsedTime = 0f;
    public CheckComplete waitComplete = () => { };
    public void WaitNow(float waitTime = 3f)
    {
        // :: Remember Wait Time
        this.waitTime = waitTime;

        // :: Start Update
        isWait = true;
    }

    // Update is called once per frame
    // ::: for Variables
    public delegate void CheckComplete();
    public CheckComplete goComplete = () => { };
    void Update()
    {
        // :: Start Go
        if(isGo)
        {
            // :: Go Toward
            this.gameObject.transform.position = Vector3.MoveTowards(this.gameObject.transform.position, this.target.transform.position, speed * Time.deltaTime);

            // :: Check Distance
            float distance = Vector3.Distance(this.gameObject.transform.position, this.target.transform.position);

            // :: When near the Cube
            if(distance <= 0.2f)
            {
                // :: Stop Go
                isGo = false;

                // :: Change Animation
                this.gameObject.GetComponent<Animation>().Play(animationName_Idle);

                // :: Send Move Complete
                this.goComplete();
            }
        }
        // :: Start Wait
        else if(isWait)
        {
            // :: Check Elapsed Time
            elapsedTime += Time.deltaTime;
            Debug.Log(elapsedTime);

            // :: When Wait is Over
            if(elapsedTime >= waitTime)
            {
                // :: Stop Wait
                isWait = false;

                // :: Send Wait Complete
                this.waitComplete();
            }
        }
    }
}
블로그 이미지

RIsN

,

::目標まで移動してヒットするのを作ってみよう。

:2020-10-28

 

youtu.be/-pV261uo324

>>たくさん、コメントを入れよう!(自分及び相手が理解しやすいように!)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class App : MonoBehaviour
{
    // :: Variables
    List<GameObject> unitz;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Hello Start");

        // :: Initialise
        unitz = new List<GameObject>();

        // :: Load Resource
        var prefab = Resources.Load<GameObject>("Prefabs/ch_03_01");

        // :: Render and Set Position with prefab : Character A
        unitz.Add(Object.Instantiate(prefab));
        unitz[0].transform.position = new Vector3(0.5f, 0, 0);
        unitz[0].transform.eulerAngles = new Vector3(0, -90, 0);
        unitz[0].AddComponent<Hero>();

        // :: Render and Set Position with prefab : Character B
        unitz.Add(Object.Instantiate(prefab));
        unitz[1].transform.position = new Vector3(-0.5f, 0, 0);
        unitz[1].transform.eulerAngles = new Vector3(0, 90, 0);
        unitz[1].AddComponent<Hero>();

        // :: Initialise Button Continuous Attack
        Button btnContinuous = GameObject.Find("ButtonA").GetComponent<Button>();
        btnContinuous.onClick.AddListener(() =>
        {
            // :: Start Attack
            unitz[0].GetComponent<Hero>().StartAttack();
        });

        // :: Initialise Button Go target and attack
        Button btnAttack = GameObject.Find("ButtonB").GetComponent<Button>();
        btnAttack.onClick.AddListener(() =>
        {
            // :: Start Attack
            unitz[0].GetComponent<Hero>().GoTargetAndAttack(unitz[1]);
        });

        // :: Initialise Button Get Back
        Button btnGetBack = GameObject.Find("ButtonC").GetComponent<Button>();
        btnGetBack.onClick.AddListener(() =>
        {
            // :: Get Back Base Position
            unitz[0].GetComponent<Hero>().GetBack();
        });

    }

    // Update is called once per frame
    void Update()
    {
    }
}
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hero : MonoBehaviour
{
    // Start is called before the first frame update
    Vector3 basePosition;
    void Start()
    {
        // :: Initialise
        deadlineAttackTime = new float[continuousAttack.Length];
        for (int i = 0; i < continuousAttack.Length; i++)
        {
            // :: Remember Deadline Length in variable
            Animation anim = this.gameObject.GetComponent<Animation>();
            deadlineAttackTime[i] = anim[continuousAttack[i]].length;
        }
        // :: Remember Base Position
        basePosition = this.gameObject.transform.position;
    }

    // :: Get Back position
    public void GetBack()
    {
        // :: Reset Position
        this.gameObject.transform.position = basePosition;

        // :: Reset Target
        target = null;
        isNearTheTarget = false;
    }
    
    // :: Start Continuous Attack
    public void StartAttack()
    {
        // :: Start Update
        checkContinuousAttack = true;

        // :: Initialise
        continuousIndex = 1;
        elapsedTime = 0;
        this.didHit = false;
    }

    // :: Go There
    bool checkGo = false; // :: Check Go
    GameObject target; // :: Target
    bool isNearTheTarget = false; // :: Is near the Target;

    // :: Go Target And Attack
    public void GoTargetAndAttack(GameObject target)
    {
        // :: Input Target
        this.target = target;

        // :: Go
        checkGo = true;

        // :: Run Loop
        this.gameObject.GetComponent<Animation>().Play("run@loop");
    }

    bool checkContinuousAttack = false; // :: Check Continuous Attack;
    bool didHit; // :: Check Hit
    private int continuousIndex; // :: Continuous Attack Index
    private float[] hitTimeForContinuousAttack = { 0f, 0.34f, 0.5f, 0.5f };
    private string[] continuousAttack = { "idle@loop", "attack_sword_01", "attack_sword_02", "attack_sword_03" }; // :: Continuous Attack List
    private float[] deadlineAttackTime; // :: Deadline Lengths
    private float elapsedTime; // :: Elapsed Time

    // Update is called once per frame
    void Update()
    {        // :: Check Continuous is True
        if (this.checkContinuousAttack)
        {
            // :: Play Animation
            this.gameObject.GetComponent<Animation>().Play(continuousAttack[continuousIndex]);
            // :: Elapsed Time
            elapsedTime += Time.deltaTime;
            Debug.Log(elapsedTime);

            // :: When Near the Target & hitTiming
            if(this.isNearTheTarget == true && elapsedTime >= hitTimeForContinuousAttack[continuousIndex] && this.didHit == false)
            {
                // :: When hitTime is Exist
                if(hitTimeForContinuousAttack[continuousIndex] > 0)
                {
                    Debug.LogFormat("Hit! : {0}", continuousIndex);
                    Debug.Log(hitTimeForContinuousAttack[continuousIndex]);

                    // :: Animation Reset
                    target.GetComponent<Animation>().Rewind();

                    // :: Hit Animation
                    target.GetComponent<Animation>().Play("damage");

                    // :: Reset didHit
                    this.didHit = true;
                }
            }

            // :: If elapsedTime is bigger than deadlineAttackTime
            if (elapsedTime >= deadlineAttackTime[continuousIndex])
            {
                // :: ElapsedTime Reset
                elapsedTime = 0;

                // :: Next Index
                continuousIndex += 1;

                // :: If Continuous Index is Out of Range
                if (continuousIndex >= continuousAttack.Length)
                {
                    // :: Continuous Index Reset : idle@loop
                    continuousIndex = 0;

                    // :: Don't more
                    checkContinuousAttack = false;
                }

                // :: Show Next Animation;
                this.gameObject.GetComponent<Animation>().Play(continuousAttack[continuousIndex]);

                // :: didHit Reset
                this.didHit = false;
            }
        }

        // ::: Check Going
        if(this.checkGo)
        {
            // :: Check Target Distance
            float distance = Vector3.Distance(this.gameObject.transform.position, this.target.transform.position);
            // ::: when distance is near
            if(distance <= 0.35f)
            {
                // ::: Stop and Attack;
                this.checkGo = false;
                this.StartAttack();
                this.isNearTheTarget = true;
            }
            // :: Move Toward
            this.transform.position = Vector3.MoveTowards(this.transform.position, this.target.transform.position, 0.1f * Time.deltaTime);
        }
    }
}

>> 2nd Version : Vector3.MoveTowardsを使わずにTranslateでやってみよう。 

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hero : MonoBehaviour
{
    // Start is called before the first frame update
    Vector3 basePosition;
    void Start()
    {
        // :: Initialise
        deadlineAttackTime = new float[continuousAttack.Length];
        for (int i = 0; i < continuousAttack.Length; i++)
        {
            // :: Remember Deadline Length in variable
            Animation anim = this.gameObject.GetComponent<Animation>();
            deadlineAttackTime[i] = anim[continuousAttack[i]].length;
        }
        // :: Remember Base Position
        basePosition = this.gameObject.transform.position;
    }

    // :: Get Back position
    public void GetBack()
    {
        // :: Reset Position
        this.gameObject.transform.position = basePosition;

        // :: Reset Target
        target = null;
        isNearTheTarget = false;
    }
    
    // :: Start Continuous Attack
    public void StartAttack()
    {
        // :: Start Update
        checkContinuousAttack = true;

        // :: Initialise
        continuousIndex = 1;
        elapsedTime = 0;
        this.didHit = false;
    }

    // :: Go There
    bool checkGo = false; // :: Check Go
    GameObject target; // :: Target
    bool isNearTheTarget = false; // :: Is near the Target;

    // :: Go Target And Attack
    public void GoTargetAndAttack(GameObject target)
    {
        // :: Input Target
        this.target = target;

        // :: Look at Target
        this.transform.LookAt(target.transform);

        // :: Go
        checkGo = true;

        // :: Run Loop
        this.gameObject.GetComponent<Animation>().Play("run@loop");
    }

    bool checkContinuousAttack = false; // :: Check Continuous Attack;
    bool didHit; // :: Check Hit
    private int continuousIndex; // :: Continuous Attack Index
    private float[] hitTimeForContinuousAttack = { 0f, 0.34f, 0.5f, 0.5f };
    private string[] continuousAttack = { "idle@loop", "attack_sword_01", "attack_sword_02", "attack_sword_03" }; // :: Continuous Attack List
    private float[] deadlineAttackTime; // :: Deadline Lengths
    private float elapsedTime; // :: Elapsed Time

    // Update is called once per frame
    void Update()
    {        // :: Check Continuous is True
        if (this.checkContinuousAttack)
        {
            // :: Play Animation
            this.gameObject.GetComponent<Animation>().Play(continuousAttack[continuousIndex]);
            // :: Elapsed Time
            elapsedTime += Time.deltaTime;
            Debug.Log(elapsedTime);

            // :: When Near the Target & hitTiming
            if(this.isNearTheTarget == true && elapsedTime >= hitTimeForContinuousAttack[continuousIndex] && this.didHit == false)
            {
                // :: When hitTime is Exist
                if(hitTimeForContinuousAttack[continuousIndex] > 0)
                {
                    Debug.LogFormat("Hit! : {0}", continuousIndex);
                    Debug.Log(hitTimeForContinuousAttack[continuousIndex]);

                    // :: Animation Reset
                    target.GetComponent<Animation>().Rewind();

                    // :: Hit Animation
                    target.transform.LookAt(this.transform);
                    target.GetComponent<Animation>().Play("damage");

                    // :: Reset didHit
                    this.didHit = true;
                }
            }

            // :: If elapsedTime is bigger than deadlineAttackTime
            if (elapsedTime >= deadlineAttackTime[continuousIndex])
            {
                // :: ElapsedTime Reset
                elapsedTime = 0;

                // :: Next Index
                continuousIndex += 1;

                // :: If Continuous Index is Out of Range
                if (continuousIndex >= continuousAttack.Length)
                {
                    // :: Continuous Index Reset : idle@loop
                    continuousIndex = 0;

                    // :: Don't more
                    checkContinuousAttack = false;
                }

                // :: Show Next Animation;
                this.gameObject.GetComponent<Animation>().Play(continuousAttack[continuousIndex]);

                // :: didHit Reset
                this.didHit = false;
            }
        }

        // ::: Check Going
        if(this.checkGo)
        {
            // :: Check Target Distance
            float distance = Vector3.Distance(this.gameObject.transform.position, this.target.transform.position);
            Debug.Log(distance);
            // ::: when distance is near
            if(distance <= 0.35f)
            {
                // ::: Stop and Attack;
                this.checkGo = false;
                this.StartAttack();
                this.isNearTheTarget = true;
            }

            // :: Move There with Translate
            this.transform.Translate(this.transform.forward * 0.1f * Time.deltaTime, Space.World);

            // :: Move Toward
            //this.transform.position = Vector3.MoveTowards(this.transform.position, this.target.transform.position, 0.1f * Time.deltaTime);
        }
    }
}
블로그 이미지

RIsN

,