2016-06-14 1 views
0

MonoGame 및 C#으로 시작한 것입니다. 객체 목록에 1 개의 이미지를 사용하려고 시도했습니다. .Monogame 및 C#, 동일한 이미지를 가진 여러 객체를 목록에로드하면 모두 동일한 속성을 얻음

나는 1 개의 이미지로 20 개의 풍선을 만들려고 노력하고 있지만, 모두 다른 위치와 타이머를 가져야합니다. 그것들은 루프 0-19의 List에 추가됩니다. 각 반복마다 새로운 Balloon (이미지)을 만들고 생성자는 임의의 시작점과 타이머를 제공하고 이미지는 매개 변수에서 가져옵니다.

문제는 내가 목록에있는 모든 풍선이 루프가 완료된 후에 추가 된 마지막 풍선의 값을 얻는다는 것인데, 이는 모두 동일한 객체 였지만 새로운 것 한 번 매번 여기에 무슨 일이 일어나고 있는지 전혀 모른다. ??

풍선 클래스 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 

namespace Game1 
{ 
    public class Balloon 
{ 
    private const int SCREEN_WIDTH = 640; 
    private const int SCREEN_HEIGHT = 480; 
    private const int MIN_VELOCITY = 30; 

    //picture from contents 
    private Texture2D image; 
    //balloons current position 
    private Vector2 position; 
    //how fast its moving 
    private Vector2 velocity; 
    private bool moving; 
    //timer, so they can pop up at a diferent time, number 1-9 
    private int timer; 


    public Balloon(Texture2D image) 
    { 
     this.image = image; 
     setRandomPosition(); 
     setRandomTimer(); 
     //no balloon is moving when initialsied 
     moving = false; 
     //start with 0 speed 
     velocity = new Vector2(0.0f, 0.0f); 
    } 

    //sets random X for the balloon, with Y just out of screen visible area 
    public void setRandomPosition() 
    { 
     position = new Vector2(new Random().Next(SCREEN_WIDTH), SCREEN_HEIGHT + 1); 
    } 

    //number 1-9 , balloon starts moving when seconds elapsed % timer is 0 
    public void setRandomTimer() 
    { 
     timer = new Random().Next(1, 10); 
    } 

    private void calculateRandomVelocity() 
    { 
     velocity = new Vector2(velocity.X, new Random().Next(50) + MIN_VELOCITY); 
    } 

    //starts moving the balloon by subtracting the Y 
    public void go(GameTime gameTime) 
    { 
     moving = true; 
     calculateRandomVelocity(); 
     //subtract Y so balloon goes up 
     position -= velocity * (float)gameTime.ElapsedGameTime.TotalSeconds; 
    } 

    //stops the balloon and sets random X with Y outside visible area 
    public void stop() 
    { 
     moving = false; 
     setRandomPosition(); 
    } 

    //--------Getters and Setters------------// 

    public Vector2 getPosition() 
    { 
     return position; 
    } 

    public void setMoving(bool moving) 
    { 
     this.moving = moving; 
    } 

    public bool isMoving() 
    { 
     return moving; 
    } 

    public Texture2D getImage() 
    { 
     return image; 
    } 

    public void setImage(Texture2D image) 
    { 
     this.image = image; 
    } 

    public int getTimer() 
    { 
     return timer; 
    } 
} 

} 

게임 클래스 :

using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 

namespace Game1 
{ 

public class Game1 : Game 
{ 
    const int NUM_BALLOONS = 20; 

    GraphicsDeviceManager graphics; 
    SpriteBatch spriteBatch; 
    List<Balloon> balloons; 

    public Game1() 
    { 
     Content.RootDirectory = "Content"; 
     graphics = new GraphicsDeviceManager(this); 
    } 

    protected override void Initialize() 
    { 
     base.Initialize(); 
    } 

    protected override void LoadContent() 
    { 
     spriteBatch = new SpriteBatch(GraphicsDevice); 

     loadBalloonsIntoList();   
    } 

    public void loadBalloonsIntoList() 
    { 
     balloons = new List<Balloon>(); 

     Texture2D image = Content.Load<Texture2D>("balloon"); 
     //load 20 balloons into the list 
     //after loading here it ends up with same properties - exact same object for all the elements 
     //they all take the values from the last one added 
     for (int i = 0; i < NUM_BALLOONS; i++) 
     { 
      Balloon b = new Balloon(image); 
      balloons.Add(b); 
     } 
    } 

    public void moveBalloons(GameTime gameTime) 
    { 
     foreach(Balloon b in balloons) 
     { 
      //cant be 0 because all balloons would start on first iteration, start moving a balloon that is not moving already 
      //and its time has come 
      if (gameTime.ElapsedGameTime.Seconds > 0 && gameTime.ElapsedGameTime.Seconds % b.getTimer() == 0 && !b.isMoving()) 
      { 
       b.go(gameTime); 
      } 
      //stop the balloon when it goes out of visible area 
      if (b.getPosition().Y <= 0) 
      { 
       b.stop(); 
      } 
     } 
    } 

    protected override void UnloadContent() 
    { 

    } 

    protected override void Update(GameTime gameTime) 
    { 
     moveBalloons(gameTime); 
    } 

    protected override void Draw(GameTime gameTime) 
    { 
     GraphicsDevice.Clear(Color.White); 

     spriteBatch.Begin(); 

     foreach(Balloon b in balloons) 
     { 
      spriteBatch.Draw(b.getImage(), b.getPosition(), Color.White);  
     } 

     spriteBatch.End(); 

    } 
} 
} 

답변

2

귀하의 setRandomPosition 방법은 각각의 호출로 임의의 클래스의 새 인스턴스를 만듭니다. 20 개의 풍선이 연속적으로 (즉, 루프 내에서) 연속적으로 인스턴스화되기 때문에, 새로운 각 Random 클래스 인스턴스는 동일한 시드 값으로 끝날 가능성이 높으므로 동일한 "임의"값을 출력합니다. 따라서 모든 풍선 객체는 같은 좌표로 끝납니다. 클래스 레벨에서 static 랜덤 인스턴스 하나를 대신 만들어보십시오. https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx

에서

는 기본 시드 값은 시스템 클럭에서 파생 된 유한 해상도를 가지고있다. 결과적으로 에서 생성 된 다른 임의 개체는 기본 생성자를 호출하여 연속하여 연속으로 과 동일한 기본 시드 값을 가지므로 동일한 개의 임의 숫자 집합을 생성합니다.

+0

대단히 감사합니다. 그게 내 마음을 완전히 미끄러 뜨 렸어. –

관련 문제