커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
캐릭터 속도가 떨어졌어요.
게임개발 종합반 v7
기타
북마크
송*철
댓글
5
추천
0
조회수
22
조회수
22
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.



배경이미지 4가지만 추가해도 속도가 떨어지네요.



스파르타 즉문즉답




작성한 코드 및 에러 메세지

속도를 증가시키기 위해 작성한 캐릭터 코드입니다. 별로 효과가 없어요.  

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


public class rtan : MonoBehaviour
{
    internal static float speed;
    private float direction = 0.1f;
    private float toward = 1.0f;
    public float moveSpeed = 12f;
    public float jumpForce = 12f;
    
    public GameObject starPrefab;
    public Transform starSpawnPoint;
    public float starForce = 12f;
    
    private Rigidbody2D rb;
    float power = 20f;
    private bool isGrounded;
    private Vector2 velocity;
    
    private float horizontal;
    private float vertical;
    private object stick;
    private readonly int score;
    
    public int Speed { get; private set; }


    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        velocity = Vector2.zero;
    }


    // Update is called once per frame
    private void Update()
    {
        if (transform.position.x > 2.8f)
        {
            direction = -0.1f;
            toward = -1.0f;
        }
        if (transform.position.x < -2.8f)
        {
            direction = 0.1f;
            toward = 1.0f;
        }
        if (Input.GetMouseButtonDown(0))
        {
            direction *= -1;
            toward *= -1;
        }
        transform.localScale = new Vector3(toward, 1, 1);
        transform.position += new Vector3(direction, 0.0f, 0.0f);
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.localScale = new Vector3(-1, 1, 1);
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.localScale = new Vector3(1, 1, 1);
        }


        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
            isGrounded = false;
        }


        if (rtanManager.score >= 100)
        {
            for (int i = 0; i < 5; i++)
            {
                GameObject starPrefab = Resources.Load<GameObject>("Prefabs/star");
                Vector3 spawnPos = new Vector3(UnityEngine.Random.Range(-2f, 2f), 6f, 0f);
                GameObject star = Instantiate(starPrefab, spawnPos, Quaternion.identity);
                star.transform.parent = transform;
            }
        }


        if (rtanManager.score >= 300) // check if score is >= 1500
        {
            if (!GameObject.Find("crown")) // if the crown does not exist
            {
                GameObject crown = Instantiate(starPrefab, transform.position + new Vector3(0, 0.5f, 0), Quaternion.identity); // create a new crown at rtan's position
                crown.name = "crown"; // set the name of the crown to "crown"
                crown.transform.parent = transform; // make the crown a child of rtan
            }
        }
    }


    private void FixedUpdate()
    {
        rb.velocity = velocity;


        float horizontalInput = Input.GetAxis("Horizontal");
        velocity.x = horizontalInput * moveSpeed;
        velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
        rb.velocity = new Vector3(horizontal, -1, vertical) * speed;
        
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "ground")
        {
            isGrounded = true;
        }
    }
}





using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using Random = System.Random;
using System.IO;
using UnityEngine.Networking;


public class gameManager : MonoBehaviour
{
    public GameObject rain;
    public GameObject redrain;
    public Text scoreText;
    public Text timeText;
    public GameObject star;
    public GameObject crown;


    public GameObject panel;


    public static gameManager I;
    private int totalScore = 0;
    private float limit = 250.0f;
    private bool crownAndStarEnabled = false;
    private bool starsCreated = false;
    private bool crownCreated = false;
    private bool starEnabled = false;
    public GameObject starPrefab;
    public float starLifetime = 5f;
    private Vector3 randomPos;
    public GameObject[] backgroundImages;
    private int backgroundIndex = 0;
    private AudioSource bgmSource;
    private List<GameObject> stars = new List<GameObject>();
    public int numStars = 60;
    public Vector2 screenBounds = new Vector2(5, 5);
    public float minScale = 0.05f;
    public float maxScale = 0.12f;
    public Color minColor = Color.white;
    public Color maxColor = Color.yellow;
    public float starSpeed = 30f;
    public float starCreationInterval = 0.1f;
    public float backgroundChangeInterval = 10f;
    private AudioSource CgmSource;
    private float lastBackgroundChangeTime = 0f;
    public GameObject backimage1;
    public GameObject backimage2;
    public GameObject backimage3;
    public GameObject backimage4;
    private bool crownEnabled;
    private Func<IEnumerator> GetCreateStarsCoroutine;
    private object go;
    private int i;


    private void Awake()
    {
        I = this;
    }


    private void Start()
    {
        InvokeRepeating("makeRain", 0.0f, 0.5f);
        InvokeRepeating("makeRedrain", 0.0f, 0.5f);
        initGame();


    }


    private void initGame()
    {
        Time.timeScale = 1.0f;
        limit = 250.0f;
        totalScore = 0;
        crownCreated = false;
        starEnabled = false;
        crownAndStarEnabled = false;
    }


    private void makeRain()
    {
        Instantiate(rain);
    }


    private void makeRedrain()
    {
        Instantiate(redrain);
    }


    private void Update()
    {
        limit -= Time.deltaTime;


        if (limit < 0)
        {
            limit = 0.0f;
            panel.SetActive(true);
            Time.timeScale = 0.0f;
        }


        timeText.text = limit.ToString("N2");


        if (totalScore >= 100 && !starsCreated)
        {
            starsCreated = true;
            Coroutine coroutine = StartCoroutine(CreateStarsCoroutine1);
            starEnabled = true;
        }


        if (totalScore >= 300 && !crownEnabled)
        {
            audioManager.I.CgmPlayOneShot();
            GameObject character = GameObject.Find("rtan");
            GameObject crownInstance = Instantiate(crown, character.transform.position + Vector3.up * 1.5f, Quaternion.identity);
            crownInstance.transform.parent = character.transform;
            crownInstance.transform.localPosition = new Vector3(0.0f, 0.68f, 0.0f);
            crownEnabled = true;
            StartCoroutine(GetDestroyCrownCoroutine());
        }


        UpdateBackgroundImages();


        // Move the stars
        for (int i = 0; i < stars.Count; i++)
        {
            stars[i].transform.position += new Vector3(0, -starSpeed * Time.deltaTime, 0);


            // Destroy stars that go below the screen
            if (stars[i].transform.position.y < -screenBounds.y - 1f)
            {
                Destroy(stars[i]);
                stars.RemoveAt(i);
                i--;
            }
        }
        // Change the background
        if (backgroundChangeInterval > 0 && Time.time - lastBackgroundChangeTime > backgroundChangeInterval)
        {
            lastBackgroundChangeTime = Time.time;


            switch (backgroundIndex)
            {
                case 1:
                    backimage1.SetActive(false);
                    backimage2.SetActive(true);
                    backgroundIndex = 2;
                    break;
                case 2:
                    backimage2.SetActive(false);
                    backimage3.SetActive(true);
                    backgroundIndex = 3;
                    break;
                case 3:
                    backimage3.SetActive(false);
                    backimage4.SetActive(true);
                    backgroundIndex = 4;
                    break;
                case 4:
                    backimage4.SetActive(false);
                    backimage1.SetActive(true);
                    backgroundIndex = 1;
                    break;
            }
        }
    
}
    public void PlayEventSound()
    {
        // 배경음악 재생 중이면 정지합니다.
        if (audioManager.I.bgmisPlaying)
        {
            audioManager.I.cgmStop();
        }
        else
        {
            // 이벤트 음악을 재생합니다.
            audioManager.I.CgmPlayOneShot();
        }
    }


    public void StopEventSound()
    {
        // 이벤트 음악을 정지합니다.
        audioManager.I.cgmstop();


        // 배경음악을 다시 재생합니다.
        audioManager.I.bgmPlay();
    }
    private void LoadBackgroundImages()
    {
        for (int i = 0; i < backgroundImages.Length; i++)
        {
            StartCoroutine(LoadImage("background" + (i + 1).ToString() + ".jpg", backgroundImages[i]));
        }
    }


    private IEnumerator LoadImage(string url, GameObject target)
    {
        string[] urls = new string[] { "backimge1.jpg", "backimge2.jpg", "backimge3.jpg", "backimge4.jpg" };
        List<Texture2D> textures = new List<Texture2D>();


        for (int i = 0; i < urls.Length; i++)
        {
            string path = System.IO.Path.Combine(Application.streamingAssetsPath, urls[i]);
            UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
            yield return www.SendWebRequest();


            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
                textures.Add(texture);
            }
        }


        // Do something with the loaded textures
        foreach (Texture2D texture in textures)
        {
            // do something with texture
        }
    }


    private IEnumerator CreateStarsCoroutine()
    {
        for (int i = 0; i < 60; i++)
        {
            GameObject starInstance = Instantiate(star);
            starInstance.transform.position = new Vector3(UnityEngine.Random.Range(-4.0f, 4.0f), UnityEngine.Random.Range(8.0f, 8.0f), 0.0f);
            StartCoroutine(DestroyStarCoroutine(starInstance));
            yield return new WaitForSeconds(0.5f);
        }
        yield return new WaitForSeconds(19.5f); // wait for 20 seconds after creating stars
        starsCreated = false; // reset the variable to allow stars to be created again
    }


    private IEnumerator DestroyStarCoroutine(GameObject starInstance)
    {
        yield return new WaitForSeconds(5.0f);
        Destroy(starInstance);
    }


   
    private IEnumerator CreateStarsCoroutine1
    {
        get
        {
            while (true)
            {
                if (starEnabled)
                {
                    if (stars.Count < numStars)
                    {
                        GameObject newStar = Instantiate(starPrefab);
                        newStar.transform.position = new Vector3(UnityEngine.Random.Range(-screenBounds.x, screenBounds.x), UnityEngine.Random.Range(-screenBounds.y, screenBounds.y), 0);
                        newStar.transform.localScale = new Vector3(UnityEngine.Random.Range(minScale, maxScale), UnityEngine.Random.Range(minScale, maxScale), 1);
                        newStar.GetComponent<SpriteRenderer>().color = Color.Lerp(minColor, maxColor, UnityEngine.Random.Range(0f, 1f));
                        stars.Add(newStar);
                    }
                    yield return new WaitForSeconds(starCreationInterval);
                }
                else
                {
                    yield return null;
                }
            }
        }
    }


    void UpdateBackgroundImages()
    {
        if (Time.frameCount % 3000 == 0)
        {
            switch (backgroundIndex)
            {
                case 1:
                    backimage1.SetActive(false);
                    backimage2.SetActive(true);
                    backgroundIndex = 2;
                    break;
                case 2:
                    backimage2.SetActive(false);
                    backimage3.SetActive(true);
                    backgroundIndex = 3;
                    break;
                case 3:
                    backimage3.SetActive(false);
                    backimage4.SetActive(true);
                    backgroundIndex = 4;
                    break;
                case 4:
                    backimage4.SetActive(false);
                    backimage1.SetActive(true);
                    backgroundIndex = 1;
                    break;
            }
        }
    }


    private string CreateAndDestroyStars()
    {
        throw new NotImplementedException();
    }


    internal int getTotalScore()
    {
        throw new NotImplementedException();
    }
    public void SpawnStar()
    {
        // Generate a random position for the star


        // Instantiate a new star at the random position
        GameObject newStar = Instantiate(starPrefab, randomPos, Quaternion.identity);


        // Set the parent of the new star to the GameManager object in the scene hierarchy
        newStar.transform.SetParent(transform);


        // Schedule the star to be destroyed after some time
        Destroy(newStar, starLifetime);
    }
    private IEnumerator CreateStarsCoroutine2
    {
        get
        {
            for (int i = 0; i < 60; i++)
            {
                // Generate a random position for the star
                Vector3 randomPos = new Vector3(UnityEngine.Random.Range(-2.0f, 2.0f), UnityEngine.Random.Range(3.0f, 6.0f), 0.0f);


                // Instantiate a new star at the random position
                GameObject starInstance = Instantiate(star, randomPos, Quaternion.identity);


                // Schedule the star to be destroyed after some time
                StartCoroutine(DestroyStarCoroutine(starInstance));
                yield return new WaitForSeconds(1.0f);
            }
        }
    }


    private string DestroyStarCoroutine1(GameObject starInstance)
    {
        throw new NotImplementedException();
    }


    private IEnumerator GetDestroyCrownCoroutine()
    {
        yield return new WaitForSeconds(5f);
        crownEnabled = false;
        crownCreated = false;
    }


    private void Destroy(object starInstance)
    {
        throw new NotImplementedException();
    }


    private IEnumerator GetDestroyCrownCoroutine1()
    {
        yield return new WaitForSeconds(70.0f);
        GameObject character = GameObject.Find("rtan");
        Destroy(character.transform.Find("crown(Clone)").gameObject);
    }


    public void addScore(int score)
    {
        totalScore += score;
        scoreText.text = totalScore.ToString();
    }


    public void retry()
    {
        SceneManager.LoadScene("MainScene");
        crownAndStarEnabled = false;
    }


}

취소
 공유
취소
댓글 0
댓글 알림
나의얼굴