백준 9012 : 괄호 // 성공

C# 2020. 10. 31. 22:37

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고 부른다. 한 쌍의 괄호 기호로 된 “( )” 문자열은 기본 VPS 이라고 부른다. 만일 x 가 VPS 라면 이것을 하나의 괄호에 넣은 새로운 문자열 “(x)”도 VPS 가 된다. 그리고 두 VPS x 와 y를 접합(concatenation)시킨 새로운 문자열 xy도 VPS 가 된다. 예를 들어 “(())()”와 “((()))” 는 VPS 이지만 “(()(”, “(())()))” , 그리고 “(()” 는 모두 VPS 가 아닌 문자열이다.

여러분은 입력으로 주어진 괄호 문자열이 VPS 인지 아닌지를 판단해서 그 결과를 YES 와 NO 로 나타내어야 한다. 

입력 데이터는 표준 입력을 사용한다. 입력은 T개의 테스트 데이터로 주어진다. 입력의 첫 번째 줄에는 입력 데이터의 수를 나타내는 정수 T가 주어진다. 각 테스트 데이터의 첫째 줄에는 괄호 문자열이 한 줄에 주어진다. 하나의 괄호 문자열의 길이는 2 이상 50 이하이다. 

:: 성공

: 요점은 char 사용을 기피해야 한다는 것

: 첫 코드가 char를 사용해서 확인했는데 양쪽 괄호를 동일하게 인식해서 문제가 생김, toString()을 활용함

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack03
{
    class Program
    {
        static void Main(string[] args)
        {
            int commandSize = Int32.Parse(Console.ReadLine()); // :: Command Size

            // :: Rotation Input
            for (int i = 0; i < commandSize; i++)
            {
                // :: Initialise
                Stack<int> stack = new Stack<int>();
                string input = Console.ReadLine();
                string yesNo = "";
                bool isError = false;

                // :: Don't need check, because it's odd
                if(input.Length % 2 != 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }

                foreach(var itm in input)
                {
                    if (itm.ToString() == "(")
                    {
                        stack.Push(1);
                    } else
                    {
                        if(stack.Count > 0)
                        {
                            stack.Pop();
                        } else
                        {
                            isError = true;
                        }
                    }
                }

                if(isError)
                {
                    Console.WriteLine("NO");
                } else
                {
                    Console.WriteLine("{0}", stack.Count > 0 ? "NO" : "YES");
                }
            }
        }
    }
}

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 10773 : 제로 // 성공  (0) 2020.10.30
Study : Quick Sort  (0) 2020.10.26
숫자 출력 시 1000단위 구분기호 추가하는 법  (0) 2020.09.24
블로그 이미지

RIsN

,

백준 10773 : 제로 // 성공

C# 2020. 10. 30. 22:22

나코더 기장 재민이는 동아리 회식을 준비하기 위해서 장부를 관리하는 중이다.

재현이는 재민이를 도와서 돈을 관리하는 중인데, 애석하게도 항상 정신없는 재현이는 돈을 실수로 잘못 부르는 사고를 치기 일쑤였다.

재현이는 잘못된 수를 부를 때마다 0을 외쳐서, 가장 최근에 재민이가 쓴 수를 지우게 시킨다.

재민이는 이렇게 모든 수를 받아 적은 후 그 수의 합을 알고 싶어 한다. 재민이를 도와주자!

첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000)

이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다.

정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.

:: 성공

: 이전과 달리 그냥 스택을 사용

: 스택 기능 중에 SUM이 있길래 그대로 사용, 꽤 짧다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack02
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Stack<int> stack = new Stack<int>();

            int commandSize = Int32.Parse(input);
            for(int i = 0; i < commandSize; i++)
            {
                input = Console.ReadLine();
                int inputParse = Int32.Parse(input);

                if (inputParse == 0)
                {
                    stack.Pop();
                } else
                {
                    stack.Push(inputParse);
                }
            }

            Console.WriteLine(stack.Sum());
        }
    }
}

 

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
Study : Quick Sort  (0) 2020.10.26
숫자 출력 시 1000단위 구분기호 추가하는 법  (0) 2020.09.24
블로그 이미지

RIsN

,

::武器を変える。

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

,

《文法》

【Nullじゃないなら実行】

// :: Callback
Callback_CompletedFX?.Invoke();
// :: Same the above
/*if (Callback_CompletedFX != null)
{
	Callback_CompletedFX();
}*/

《EASY to USE》

【EnumのDescriptionを取得して使用】

// :: Enums : Animation Key
private enum eAnimation
{
  [Description("idle@loop")]
  IDLE,
  [Description("run@loop")]
  RUN,
  [Description("walk@loop")]
  WALK
}

// :: for use enum Description
// ::: Ref : http://kawakawa2000.jugem.jp/?eid=27
// ::: I don't understand perfectly yet.
private string GetEnumDescription(eAnimation value)
{
	FieldInfo fi = value.GetType().GetField(value.ToString());
	var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

	var descriptionString = attributes.Select(ele => ele.Description).FirstOrDefault();

	if(descriptionString != null)
	{
		return descriptionString;
	}
	return value.ToString();
}

void Update() 
{
	anim.Play(this.GetEnumDescription(eAnimation.RUN));
}

【Unity Editorにツールを登録

// :: for Using
using UnityEditor;

// :: Easy to use
public class MenuTest : MonoBehaviour
{
    // :: Location
    [MenuItem("MyMenu/Delete All PlayerPrefs")]
    // :: Program : Delete All PlayerPrefs
    static void DeleteAllPlayerPrefs()
    {
        PlayerPrefs.DeleteAll();
        Debug.Log("deleted all player prefs");
    }
}

《イベント》

【ボタンにイベントリスナーを追加】

>>クリックすると動くように

// :: Add Event Listener
btn.onClick.AddListener(this.ClickedButton);

【数秒後に実行】
>>Singletonに定義してそれを持ってきて使うのも可能

<<CT_Ruler>>
// :: Do Action after Waiting
UIController.WaitForSecondsAndDo(10f, (() => { UIController.FadeIn(GOHolder.SPRITE_handRight); }));

<<Sing_UIController>>
// :: Do Action after Waiting
public void WaitForSecondsAndDo(float time, System.Action action)
{
	this.StartCoroutine(WaitForSecondsAndDoImplement(time, action));
}
private IEnumerator WaitForSecondsAndDoImplement(float time, System.Action action)
{
	yield return new WaitForSeconds(time);
	action();
}

【ゲーム停止】

// :: Pause Game
Time.timeScale = 0;
// :: RePlay Game
Time.timeScale = 1;

《出力》

【PrefabをベースにGameObjectの複製を作ってそれを画面に出力】

// :: Make GameObject & Render
GameObject prefab =  Resources.Load<GameObject>("ch_03_01");
GameObject clone =  Instantiate<GameObject>(prefab);

【出力する際に親(Parent)と位置を設定】

// :: Render Chest Closed and Set Position
// ::: Use Transform Parent
// ::: 1. GameObject
// ::: 2. Position
// ::: 3. Rotation
// ::: 4. Parent transform
chestClosed = Object.Instantiate<GameObject>(chestPrefabA, // 1
            lastTarget.transform.position + new Vector3(0, 0, 0.5f), // 2 
            Quaternion.Euler(-90, -90, 0), // 3
            lastTarget.transform); // 4

【出力してから親(Parent)を設定】

// :: Create Weapon and Set Parent
GameObject spear = Object.Instantiate<GameObject>(Resources.Load<GameObject>("Spear_7"));
spear.transform.SetParent(dummyRHand);
// :: Change Position
spear.transform.localPosition = new Vector3(0, 0, 0);
spear.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, 0));

【画面にいるGameObjectの出力を消す】

// :: Destroy Game Object
Destroy(itm);

【3Dのキャラ位置に合わせて2DキャンバスにHUDを出力】

// :: When Button Clicked : Show HUD
this.BUTTON_test.onClick.AddListener(() =>
{
	// :: Instantiate with Canvas
	var go = Instantiate<GameObject>(this.hudPrefab, this.canvas.transform);

	// :: Check Where do you want set the position
	// ::: Main Camera World Point => Screen Point
	var screenPoint = Camera.main.WorldToScreenPoint(playerGO.transform.position);

	// ::: Screen Point => Local(Canvas) Point
	Vector2 localPoint;
	// ::: ((RectTransform) Canvas Transform, Screen Point, Camera which you will set HUD, out local Point)
	RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)canvas.transform, screenPoint, this.uiCam, out localPoint);

	// :: Change HUD Local position
	go.transform.localPosition = localPoint;

	// :: Play and Destroy
	var hud = go.GetComponent<HUDText>();
	hud.Init(992);
	hud.Play();
	hud.Callback_Play = () => {
		Destroy(hud.gameObject);
	};
});

《方向と移動》

【1歩前に動く:マップ基準】

// :: Map Position
hero.transform.position += Vector3.forward;
//this.gameObject.transform.Translate(Vector3.forward, Space.Self);

1歩前に動く:自分基準】

// :: Self Position
hero.transform.position += hero.transform.forward;
//this.gameObject.transform.Translate(this.transform.forward, Space.World);

【目標の方向を見るように角度を修正】

// :: Look target Direction
Vector3 target = new Vector3(1, 0.49f, -2) - itm.transform.position;
itm.transform.rotation = Quaternion.LookRotation(target);

【目標を見てその方向に走る(結果:目標を通って走る)】

// :: Look at Target
this.transform.LookAt(target.transform);
// :: 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);

《衝突》

【衝突無視】

// :: Find all BoxCollider2D
foreach (var itm in GameObject.FindObjectsOfType<BoxCollider2D>())
{
	// :: Player : Ignore it
	Physics2D.IgnoreCollision(playerRigidbody.gameObject.GetComponent<CircleCollider2D>(), itm, true);
}

【RayCastで衝突感知】

// :: Hit Checker
RaycastHit hit;
// :: When Racast Hit
// ::: (Start Position, Direction, Hit Object, Max Distance)
if (Physics.Raycast(this.player.transform.position, this.player.transform.forward, out hit, 1f))
{
	// :: Check Hit Object's Name
	Debug.Log(hit.transform.gameObject.name);
	// :: Show ray for Debug
	Debug.DrawRay(this.player.transform.position, this.player.transform.forward * 1f, Color.red);
}

《SCENE移動》

【SCENE移動時に完了をチェック、そしてその後に何かを実行】

// :: Load Scene with Done Checker
UnityEngine.AsyncOperation async = SceneManager.LoadSceneAsync(this.GetEnumDescription(sceneType));
// :: When Scene Load Completed
async.completed += Async_completed;

// :: Do Action
private void Async_completed(UnityEngine.AsyncOperation obj)
{
	if(obj.isDone)
	{
    	Debug.Log("Load Completed");
	}
}

 

블로그 이미지

RIsN

,

D3 : 1 Page Plan

_Dogma 2020. 10. 27. 09:24

프로젝트명 : Dogma 3
게임(가제) : Dogma / Letter
언어 : 영어

 

간단 설명 : 던전 RPG(: 세계수의 미궁)로써 Dogma 2에 이은 스토리형 게임
컨셉 : 아포칼립스(Fallout 4 스타일), 사막, (Damn Crab)
사용 툴 : 유니티(3D? 2D?) // 2D로 가능할 경우 2D를 선호
플레이타임 : 1시간

 

목표 다운로드 수 : 100
목표 수익 : $10
수익 창출 수단 : 광고(Admob), 후원(Patreon)
마케팅 수단 : Twitter(#indie)

 

<상세 스토리 설명>

레드 랍스터에게서 도망치다가 어디가로 떨어져버린 플레이어와 송, 유적인 듯 방공호인 듯한 이곳에서 나가기 위해 탐험을 시작하는데

<초기 개발 제한>
: 캠프(아이템 구매 및 회복 등) / 던전
캐릭터 수 : 2(플레이어는 이미지 없음)
: 12x12 2(튜토리얼 5x5 제외) // 동일 디자인
몬스터 수 : 1마리
보스 : 1마리

 

업데이트 : 2020-10-28

'_Dogma' 카테고리의 다른 글

Dogma / Coin Expansion 0.1 is decided  (0) 2021.03.14
Project D2 : Dogma / Coin is Release Now!  (0) 2020.12.12
블로그 이미지

RIsN

,

Study : Quick Sort

C# 2020. 10. 26. 22:56

<퀵 정렬>

  :: 간략 정보

    - 가장 빠른 정렬 알고리즘

    - 자기 자신을 불러 쪼개서 정렬을 함

    - 수학적으로 이해해야 해서 더럽게 어려움

  :: 구조

    - 완벽하게 이해 못해서 못쓰겠음

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study33_QuickSort
{
    public class App
    {
        public App()
        {
            // :: Testing Value
            int[] arr = new int[10] { 4, 8, 7, 6, 9, 1, 3, 2, 0, 5 };
            this.ShowArray(arr);

            this.QuickSort(arr, 0, arr.Length - 1);

            this.ShowArray(arr);

        }

        public void QuickSort(int[] arr, int indexStart, int indexEnd)
        {
            // :: Null Break;
            if (indexStart >= arr.Length)
                return;

            int target = arr[indexStart];
            int left = indexStart + 1;
            int right = indexEnd;

            while(left <= right)
            {
                // :: When target is bigger than Left Value : Skip
                while(arr[left] < target)
                {
                    left += 1;

                    // :: Null Break;
                    if (left >= arr.Length)
                        break;
                }
                // :: When target is smaller than Right Value : Skip
                while (arr[right] > target)
                {
                    right -= 1;

                    // :: Null Break;
                    if (right < 0)
                        break;
                }

                // :: I didn't understand this yet.
                if(left <= right)
                {
                    SwapArray(arr, left, right);
                }
            }            

            // :: I didn't understand this yet.
            // :: Until Start index is same End index : It means dividing is one now.
            if(indexStart < indexEnd)
            {
                // :: Swap target and Right Value
                SwapArray(arr, indexStart, right);

                QuickSort(arr, indexStart, right - 1); // :: Front
                QuickSort(arr, right + 1, indexEnd); // :: End
            }

            return;
        }

        public void SwapArray(int[] arr, int a, int b)
        {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }

        public void ShowArray(int[] arr)
        {
            foreach(var itm in arr)
            {
                Console.Write("[{0}]", itm);
            }
            Console.WriteLine("");
        }

        public void Today()
        {
            DateTime today = new DateTime(2020, 10, 26);
            Console.WriteLine(today.ToString("yyyy-MM-dd") + " : THINK");
        }
    }
}

 

글 업데이트 : 2020-10-26

 

참고 사이트 :

blockdmask.tistory.com/177

블로그 이미지

RIsN

,

【キャンバス】

・他のシーンにキャンバス丸ごと複製するとタッチが動かない。

⇒キャンバスは各シーンの自体のものを使おう。

【アニメーション】

・アニメーション(Damage)が終了するまで同じアニメーション(Damage)が動かない時の方法。

⇒!Animation.Rewind()!//初期化

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

【ビルド問題】

・JSONを読む時に避けるべきの文法

File.ReadAllText({filePath})

:Androidにビルドするとファイルの位置が変更されるので、JSONファイルなどを読めない場合がある。

 

⇒!こちらを使おう!

Resources.Load<TextAsset>({filePath})

:参考サイト:docs.unity3d.com/ScriptReference/Resources.Load.html

 

Unity - Scripting API: Resources.Load

If an asset can be found at path, it is returned with type T, otherwise returns null. If the file at path is of a type that cannot be converted to T, also returns null. The path is relative to any folder named Resources inside the Assets folder of your pro

docs.unity3d.com

:まだ意味は完全に理解していないが、こちらはAndroidビルドをしても関係なく動いた!

블로그 이미지

RIsN

,

변환 {0} => {0:#,0}

Console.WriteLine("{0:#,0}cc, {1}km/l", cc, kmLitre);

 

www.atmarkit.co.jp/ait/articles/0707/19/news143.html

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
백준 10773 : 제로 // 성공  (0) 2020.10.30
Study : Quick Sort  (0) 2020.10.26
블로그 이미지

RIsN

,