首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Monogame和C#,将具有相同图像的多个对象加载到列表中,它们都具有相同的属性

问Monogame和C#,将具有相同图像的多个对象加载到列表中,它们都具有相同的属性
EN

Stack Overflow用户
提问于 2016-06-14 21:55:07
回答 1查看 1K关注 0票数 0

我刚刚从MonoGame和C#开始,我遇到了一个问题,试图为对象列表使用1个图像。

我试着用一个图像制作20个气球,但它们都应该有不同的位置和计时器。它们被添加到循环0-19中的列表中,在每次迭代时,我创建一个新的Balloon(图),构造器给它随机的开始弦和定时器,图像从参数中获取。

我的问题是,列表中的所有气球都是在循环结束后添加的最后一个气球的值,如果它们都是相同的对象,就会这样,但是我每次都创建一个新的气球,所以不知道这里发生了什么?

气球级:

代码语言:javascript
复制
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;
    }
}

}

游戏类:

代码语言:javascript
复制
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();

    }
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-14 22:19:25

setRandomPosition方法通过每次调用创建随机类的新实例。由于20个气球正在快速地被实例化(即在一个循环中),每个新的随机类实例都可能以相同的种子值结束,因此输出相同的“随机”值。因此,所有气球对象都以相同的坐标结束。尝试在类级别上创建一个static实例。

来自https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx

默认的种子值是从系统时钟导出的,并且具有有限的分辨率。因此,通过调用默认构造函数而连续创建的不同随机对象将具有相同的缺省种子值,因此将产生相同的随机数集。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37822756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档