So Im making tetris and I dont know how to draw the blocks( L,I,Z etc) I have one block as Texture2D and every class for the blocks look like this:
namespace Tetris
{
public class ZBlock
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
public bool[,] zblock()
{
vorm = new bool[x, y];
for(int i=0; i< x; i++)
for (int j=0; j<y; j++)
{
vorm[i, j] = false;
vorm[0, 0] = true;
vorm[1, 0] = true;
vorm[1, 1] = true;
vorm[2, 1] = true;
}
Color = Color.Purple;
return vorm;
}
}
and this is the block class:
namespace Tetris
{
public class Block
{
Texture2D block;
Vector2 BlockPosition = new Vector2(30, 30);
float FallTimer;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iblock = new IBlock();
public bool[,] blockvorm()
{
bool[,] vorm;
vorm = new bool[4, 4];
vorm[3, 3] = false;
int r = Random.Next(7);
if (r == 0)
{
ZBlock.zblock();
}
else if (r == 1)
{
TBlock.tblock();
}
else if (r == 2)
{
SBlock.sblock();
}
else if (r == 3)
{
OBlock.oblock();
}
else if (r == 4)
{
JBlock.jblock();
}
else if (r == 5)
{
LBlock.lblock();
}
else if (r == 6)
{
IBlock.iblock();
}
return vorm;
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iblock; }
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
int[,] Grid = Tetris.GameWorld.TetrisGrid;
spriteBatch.Begin();
spriteBatch.Draw(?????????????);
spriteBatch.End();
}
So the problem is: I dont know how to draw those blocks (I know how to draw one block but I want the complete ones). I thought maybe ZBlock.vorm or ZBLock.zblock but both give errors.
Does anyone know how to draw the blocks?
Ok so here is a partial answer. What you want to do is basically just draw each block with a certain offset from the next block equal to: blockWidth / 2 in pixels. This means that the blocks will be correctly orientated without overlap.
Here is what you should put in the draw statement:
public void Draw(int theXPosition, int theYPosition, Color theColor, SpriteBatch theSpriteBatch, Texture2D theBlockTexture)
{
int aTextureStartX = Color * Convert.ToInt32(mBlockSize);
for (int aBlock = 0; aBlock < mNumberOfBlocks; aBlock++)
{
int aXPosition = (int)(theXPosition + (CurrentShape[Rotation, aBlock, 0] * mBlockSize));
int aYPosition = (int)(theYPosition + (CurrentShape[Rotation, aBlock, 1] * mBlockSize));
theSpriteBatch.Draw(theBlockTexture, new Rectangle(aXPosition, aYPosition, mBlockSize, mBlockSize), new Rectangle(aTextureStartX, 0, mBlockSize, mBlockSize),
}
}
This is from a blog: http://www.xnadevelopment.com/tutorials/fallingblocksyoumovetomakelines/fallingblocksyoumovetomakelines.shtml
The source code is at the top of the page.
Related
I have a script to instantiate a gameobject when the agent reaches its position, when instantiated it will randomly choose any of those 2, then 3, etc... this gameobjects belong to a parent (I use the random with childcount and getChild), however my agent won't move to the instances, just the original one. I've tried using it's position and it's localPosition and none of them works, actually if I use the local position it won't even do the set destination to the original one. I can't guess if its a navmesh problem or if there is an error with my scripting. I can add some images so if anyone can help me.
Script part:
if (plant_gameobject_father.transform.childCount != 0)
{
chosen_child = Random.Range(0, plant_gameobject_father.transform.childCount - 1);
plant_target = plant_gameobject_father.transform.GetChild(chosen_child);
Debug.Log(plant_target.transform.position);
agent_.SetDestination(plant_target.position);
Debug.Log(agent_.pathStatus);
}
Video Sample:
Navmesh working just on the original gameobject
EDIT: When using agent.remainingDistance to check how it's doing it: right after assigning the destination the remaining distance is 0, and when it "arrives" to the target it's remaining distance it's bigger than it should (I have a coroutine using yield return wait until agent.remainingDistance < 3.5f) and still it thinks it has reached destination.
I will upload full script for context understanding(it's a long one)
Could it be that the distances are too big? Mi terrain is larger that 2000 units in lenght.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class insect_IA : MonoBehaviour
{
public ciclo_dia_noche info_horas; //Programado para que haga 3 ciclos de actividad al dia y inactividad de noche.
public GameObject plant_type_small;
public GameObject plant_type_medium;
public GameObject plant_type_big;
Transform plant_target;
GameObject plant_gameobject_father;
public GameObject colmena;
public int objetivo_diario_recoleccion;
public int segundos_recoleccion_polen;
public int segundos_depositado_polen;
public int plant_selector;
public NavMeshAgent agent_;
int selector_accion;
public bool wander_is_happening;
public GameObject colmena_wander_childs;
public Transform wander_target;
public int is_performing_routine_insect;
public bool its_a_new_day;
public birth_controller puedo_reproducir;
public Collider tree_spawner1, tree_spawner2, tree_spawner3, selected_collider;
public Vector3 bounds_max, bounds_min;
public int random_number;
public float spawn_point_x, spawnpoint_z, spawnpoint_y;
public Vector3 spawn_point_tree;
public GameObject tree_big_prefab, tree_med_prefab, tree_peq_prefab;
public int chosen_child;
// Start is called before the first frame update
void Start()
{
}
private void Awake()
{
info_horas = GameObject.Find("Directional_Light").GetComponent<ciclo_dia_noche>();
plant_type_big = GameObject.Find("PLANTAS_GRAND");
plant_type_medium = GameObject.Find("PLANTAS_MED");
plant_type_small = GameObject.Find("PLANTAS_PEQ");
colmena = GameObject.Find("colmena");
puedo_reproducir = GameObject.Find("birth_controlator").GetComponent<birth_controller>();
tree_spawner1 = GameObject.Find("spawn_area1").GetComponent<Collider>();
tree_spawner2 = GameObject.Find("spawn_area2").GetComponent<Collider>();
tree_spawner3 = GameObject.Find("spawn_area3").GetComponent<Collider>();
tree_big_prefab = GameObject.Find("PLANTAS_GRAND/planta_grand");
tree_med_prefab = GameObject.Find("PLANTAS_MED/planta_med");
tree_peq_prefab = GameObject.Find("PLANTAS_PEQ/planta_peq");
agent_ = GetComponent<NavMeshAgent>();
colmena_wander_childs = colmena;
selector_accion = 0;
segundos_recoleccion_polen = 5;
segundos_depositado_polen = 5;
objetivo_diario_recoleccion = 3;
is_performing_routine_insect = 0;
its_a_new_day = true;
random_number = -1;
}
// Update is called once per frame
void Update()
{
if ((puedo_reproducir.plant_big_type.transform.childCount < puedo_reproducir.max_plant_big || puedo_reproducir.plant_med_type.transform.childCount < puedo_reproducir.max_plant_med || puedo_reproducir.plant_peq_type.transform.childCount < puedo_reproducir.max_plant_peq) && info_horas.segundos_globales < info_horas.duracion_dia)
{
insect_state();
}
if (wander_is_happening == false && puedo_reproducir.plant_big_type.transform.childCount > puedo_reproducir.max_plant_big && puedo_reproducir.plant_med_type.transform.childCount > puedo_reproducir.max_plant_med && puedo_reproducir.plant_peq_type.transform.childCount > puedo_reproducir.max_plant_peq)
{
wander_is_happening = true;
is_performing_routine_insect = 4;
StartCoroutine("regular_wander");
}
}
public void insect_state()
{
if (selector_accion == 0)
{
//Debug.Log("buscar padre arbol");
is_performing_routine_insect = 1;
selector_accion = -1;
cojo_un_padre_arbol();
selector_accion = 1;
}
if (selector_accion == 1)
{
//Debug.Log("elegir destino");
selector_accion = -2;
elijo_destino();
selector_accion = 2;
}
if (selector_accion == 2)
{
//Debug.Log("esperar a que llegue");
selector_accion = -3;
check_path();
}
if (selector_accion == 3)
{
//Debug.Log("cogiendo polen");
is_performing_routine_insect = 2;
StartCoroutine("cogiendo_polen");
}
if (selector_accion == 4)
{
//Debug.Log("de vuelta a la colmena");
selector_accion = -5;
volver_colmena();
check_path();
}
if (selector_accion == 5)
{
//Debug.Log("guardo polen");
is_performing_routine_insect = 3;
StartCoroutine("guardando_polen");
}
if (selector_accion == 6)
{
//Debug.Log("reinicio insecto");
is_performing_routine_insect = 4;
StartCoroutine("esperar_proxima_recoleccion");
}
}
public void cojo_un_padre_arbol()
{
if (puedo_reproducir.plant_big_type.transform.childCount < puedo_reproducir.max_plant_big)
{
plant_selector = 2;
}
else if (puedo_reproducir.plant_med_type.transform.childCount < puedo_reproducir.max_plant_med)
{
plant_selector = 1;
}
else if (puedo_reproducir.plant_peq_type.transform.childCount < puedo_reproducir.max_plant_peq)
{
plant_selector = 0;
}
if (plant_selector == 0)
{
plant_gameobject_father = plant_type_small;
}
if (plant_selector == 1)
{
plant_gameobject_father = plant_type_medium;
}
if (plant_selector == 2)
{
plant_gameobject_father = plant_type_big;
}
//Debug.Log("padre elegido:" + plant_gameobject_father);
}
public void elijo_destino()
{
if (plant_gameobject_father.transform.childCount != 0)
{
chosen_child = Random.Range(0, plant_gameobject_father.transform.childCount - 1);
plant_target = plant_gameobject_father.transform.GetChild(chosen_child);
Debug.Log(plant_target.transform.position);
agent_.SetDestination(plant_target.position);
Debug.Log(agent_.pathStatus);
}
else if(plant_gameobject_father.transform.childCount == 0)
{
wander_is_happening = true;
is_performing_routine_insect = 4;
StartCoroutine("regular_wander");
}
//Debug.Log(this.transform.position);
//Debug.Log("planta seleccionada: " + plant_target);
//Debug.Log(agent_.remainingDistance);
}
public void check_path()
{
StartCoroutine("esperar_destino");
}
public void volver_colmena()
{
agent_.SetDestination(colmena.transform.position);
create_plant();
}
public IEnumerator cogiendo_polen()
{
selector_accion = -4;
yield return new WaitForSeconds(segundos_recoleccion_polen);
selector_accion = 4;
}
public IEnumerator guardando_polen()
{
selector_accion = -6;
yield return new WaitForSeconds(segundos_depositado_polen);
selector_accion = 6;
}
public IEnumerator esperar_destino()
{
if (plant_target.tag == "planta_peq")
{
//Debug.Log(agent_.remainingDistance);
yield return new WaitUntil(() => agent_.remainingDistance < 1.7f);
//Debug.Log(agent_.remainingDistance);
agent_.isStopped = true;
agent_.ResetPath();
if (selector_accion == -3)
{
selector_accion = 3;
}
if (selector_accion == -5)
{
selector_accion = 5;
}
}
if (plant_target.tag == "planta_med")
{
//Debug.Log(agent_.remainingDistance);
yield return new WaitUntil(() => agent_.remainingDistance < 3.0f);
//Debug.Log(agent_.remainingDistance);
agent_.isStopped = true;
agent_.ResetPath();
if (selector_accion == -3)
{
selector_accion = 3;
}
if (selector_accion == -5)
{
selector_accion = 5;
}
}
if (plant_target.tag == "planta_grand")
{
Debug.Log(agent_.remainingDistance);
yield return new WaitUntil(() => agent_.remainingDistance < 3.5f);
Debug.Log(agent_.remainingDistance);
agent_.isStopped = true;
agent_.ResetPath();
if (selector_accion == -3)
{
selector_accion = 3;
}
if (selector_accion == -5)
{
selector_accion = 5;
}
}
}
public IEnumerator esperar_proxima_recoleccion()
{
selector_accion = -7;
yield return new WaitForSeconds(1);
selector_accion = 0;
}
public IEnumerator regular_wander()
{
wander_target = colmena_wander_childs.transform.GetChild(Random.Range(0, colmena_wander_childs.transform.childCount - 1));
agent_.SetDestination(wander_target.position);
yield return new WaitUntil(() => agent_.remainingDistance < 0.1f);
agent_.isStopped = true;
agent_.ResetPath();
yield return new WaitForSeconds(5);
wander_is_happening = false;
}
public void create_plant()
{
//Debug.Log("entro a crear una planta");
random_number = Random.Range(0, 3);
if (random_number == 0)
{
selected_collider = tree_spawner1;
}
if (random_number == 1)
{
selected_collider = tree_spawner2;
}
if (random_number == 2)
{
selected_collider = tree_spawner3;
}
bounds_max = selected_collider.bounds.max;
bounds_min = selected_collider.bounds.min;
spawn_point_x = Random.Range(bounds_min.x, bounds_max.x);
spawnpoint_z = Random.Range(bounds_min.z, bounds_max.z);
spawnpoint_y = bounds_max.y;
spawn_point_tree = new Vector3(spawn_point_x, spawnpoint_y, spawnpoint_z);
if (plant_target.tag == "planta_peq")
{
Instantiate(tree_peq_prefab, spawn_point_tree, Quaternion.identity, plant_type_big.transform);
}
if (plant_target.tag == "planta_med")
{
Instantiate(tree_med_prefab, spawn_point_tree, Quaternion.identity, plant_type_medium.transform);
}
if (plant_target.tag == "planta_grand")
{
Instantiate(tree_big_prefab, spawn_point_tree, Quaternion.identity, plant_type_big.transform);
}
Debug.Log(puedo_reproducir.plant_big_type.transform.childCount);
}
}
´´´´
There's a lot going on in your script. I'm going to put some calculated guesses here on what might help.
Your birth_controller object seems to have a separate list of all the small/medium/big plants. Are you 100% sure these reference the same as the ones in your Insect_IA object?
You are also using a lot of logic that seems very framerate dependant. Your update function itself calls insect_state() which functions as a state machine that runs through one step per frame, one frame at a time. At the same time, you start coroutines that work alongside that during all that. selector_accion is edited in both insect_state and a lot of those coroutines. Are you sure you're not deadlocking yourself out of certain values of selector_accion which are necessary for the navmesh to work?
Also: Random.Range(int minInclusive, int maxExclusive) is, for the int overload, EXCLUSIVE on the upper bound, so you can remove the -1 from plant_gameobject_father.transform.childCount - 1.
EDIT:
As discussed in the comments and in edits to the original post, the scale of your scene might be causing issues as well. If your navmesh agent cannot physically get as close as your yield WaitUntil statements are waiting for, that's probably deadlocking your logic.
I wrote some code to draw something in a iOS App, if the server send some new coordinates to it.
I have a callback function that draw the coordinates. But when I create a new instance of a class in this function the callback exit without any error...
Does someone else have this problem before?
Here is my code if this is helping
CGPath pathtotal;
List<CGPath> path;
CGPoint initialPoint;
CGPoint latestPoint;
DrawDrawerDraw drawDrawerDraw;
public DrawGuessView(IntPtr handle) : base(handle)
{
BackgroundColor = UIColor.White;
pathtotal = new CGPath();
SocketEventHandler.Add("draw:drawer:draw", onDrawDrawerDraw);
}
public void onDrawDrawerDraw(dynamic obj)
{
drawDrawerDraw = (DrawDrawerDraw)obj;
for (int i = 0; i <= drawDrawerDraw.coords.Count; i++)
{
if (initialPoint.X != (nfloat)drawDrawerDraw.coords[i].x0 && initialPoint.Y != (nfloat)drawDrawerDraw.coords[i].y0)
{
path[i] = new CGPath();
}
initialPoint.X = (nfloat)drawDrawerDraw.coords[i].x0;
initialPoint.Y = (nfloat)drawDrawerDraw.coords[i].y0;
latestPoint.X = (nfloat)drawDrawerDraw.coords[i].x1;
latestPoint.Y = (nfloat)drawDrawerDraw.coords[i].y1;
//add lines to the touch points
if (path[i].IsEmpty)
{
path[i].AddLines(new CGPoint[] { initialPoint, latestPoint });
}
else
{
path[i].AddLineToPoint(latestPoint);
}
}
SetNeedsDisplay();
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
try
{
foreach (var item in path)
{
if (!initialPoint.IsEmpty)
{
//get graphics context
using (CGContext g = UIGraphics.GetCurrentContext())
{
//set up drawing attributes
g.SetLineWidth(2);
UIColor.Black.SetStroke();
//add geometry to graphics context and draw it
pathtotal.AddPath(item);
g.AddPath(pathtotal);
g.DrawPath(CGPathDrawingMode.Stroke);
}
}
}
}
catch (Exception e) { }
}
}
There are two points you need to modify.
Initialize path in DrawGuessView method
public DrawGuessView(IntPtr handle) : base(handle)
{
BackgroundColor = UIColor.White;
pathtotal = new CGPath();
List<CGPath> path = new List<CGPath>();
SocketEventHandler.Add("draw:drawer:draw", onDrawDrawerDraw);
}
path[i] = new CGPath() will cause the ArgumentOutOfRangeException, we can't set value to the item in List by this way.
Modify the loop
CGPath pathItem = null;
for (int i = 0; i <= drawDrawerDraw.coords.Count; i++)
{
if (initialPoint.X != (nfloat)drawDrawerDraw.coords[i].x0 && initialPoint.Y != (nfloat)drawDrawerDraw.coords[i].y0)
{
pathItem = new CGPath();
}
initialPoint.X = (nfloat)drawDrawerDraw.coords[i].x0;
initialPoint.Y = (nfloat)drawDrawerDraw.coords[i].y0;
latestPoint.X = (nfloat)drawDrawerDraw.coords[i].x1;
latestPoint.Y = (nfloat)drawDrawerDraw.coords[i].y1;
//add lines to the touch points
if (pathItem.IsEmpty)
{
pathItem.AddLines(new CGPoint[] { initialPoint, latestPoint });
}
else
{
pathItem.AddLineToPoint(latestPoint);
}
path.Add(pathItem);
}
I'm currently trying to make a new class named GameButton in Visual Studio Community. im trying to put all the code into it, so that all the code is generated from the button instead of the form, but now that i moved most of the code, it either doesnt show up, or goes into an infinite loop, and im not sure how to fix it at this point. if i didnt give enough information i will supply more if needed.
(Speelveld is a form inside of the form that determines the location of the buttons. The "speelveld" is a Panel imported from the built in toolbox in visual studio. Then the code refrences to that form to build the buttons into.)
Form c#
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Marble();
}
public void Marble()
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader("Bitmap.txt");
int ButtonHeight = 40;
int y_row = 0;
GameButton testButton = new GameButton();
while ((line = file.ReadLine()) != null)
{
for (int x_row = 0; x_row < line.Count(); x_row++)
{
if(line.Substring(x_row, 1) == "1")
{
Speelveld.BackColor = Color.White;
BackColor = Color.White;
testButton.Currentcolor = false;
if (x_row == 4 && y_row == 6)
{
testButton.BackColor = Color.White;
}
else
{
Speelveld.Controls.Add(testButton);
}
}
}
y_row++;
}
}
}
}
GameButton c#
namespace WindowsFormsApplication9
{
public class GameButton: Button
{
public int Row { get; set; }
public int Column { get; set; }
public bool Currentcolor { get; set; }
Pen myPen;
public int ButtonHeight = 40;
public int y_row = 0;
public int x_row = 0;
public void Startup()
{
this.BackColor = Color.Red;
this.Height = ButtonHeight;
this.Width = ButtonHeight;
this.Top = y_row * ButtonHeight + 20;
this.Left = x_row * ButtonHeight + 20;
this.Text = "X: " + x_row.ToString() + " Y: " + y_row.ToString();
this.MouseUp += TmpButton_MouseUp;
}
protected override void OnPaint(PaintEventArgs pevent)
{
int radius = 20;
pevent.Graphics.Clear(Color.White);
Graphics graphics = pevent.Graphics;
myPen = new Pen(new SolidBrush(this.BackColor), 2f);
pevent.Graphics.FillEllipse(new SolidBrush(this.BackColor), 20 - radius, 20 - radius,
radius + radius, radius + radius);
myPen.Dispose();
}
private void TmpButton_MouseUp(object sender, MouseEventArgs e)
{
GameButton Mygamebutton = (GameButton)sender;
Mygamebutton.Currentcolor = !Mygamebutton.Currentcolor;
if (Mygamebutton.Currentcolor == true)
{
Mygamebutton.BackColor = Color.Black;
}
else
{
Mygamebutton.BackColor = Color.White;
}
}
}
}
BitMap.txt
011111110
111111111
111111111
011111110
001111100
000111000
000010000
There are several mistakes in your coed. you didn't call testButton.Startup() to set its position, also the GameButton class needs to know that x_row, y_row values...
please see following:
public void Marble()
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Main\Desktop\Bitmap.txt");
//var Speelveld = new Form3();
//Speelveld.Show();
int y_row = 0;
while ((line = file.ReadLine()) != null)
{
for (int x_row = 0; x_row < line.Count(); x_row++)
{
if (line.Substring(x_row, 1) == "1")
{
Speelveld.BackColor = Color.White;
BackColor = Color.White;
GameButton testButton = new GameButton(); // ***
testButton.Currentcolor = false;
if (x_row == 4 && y_row == 6)
{
testButton.BackColor = Color.White;
}
else
{
Speelveld.Controls.Add(testButton);
testButton.Startup(x_row , y_row); //***
}
}
}
y_row++;
}
}
and add these in GameButton startup:
public void Startup(int x, int y) //***
{
this.x_row = x; //***
this.y_row = y; //***
...
}
My friend's GameElements.cs seems to have become corrupted in some way. We're both studying in the same class, and he sent me his project and I can't open the file either. I can't troubleshoot his solution, as he is using XNA and I'm using MonoGame.
Sadly, he does not have any back-ups (this way he'll learn the hard way though) and neither one of us are familiar with neither Visual Studio nor programming at all, as we're just a couple months into the course.
The file is still 12kb, even though I can only select/copy blank spaces. I have no idea if it's possible to restore the code from it, there is obviously data in the file.
This is a link to download the whole solution, though the corrupt file in question is "GameElements.cs". We both would appreciate it greatly if someone was able to recover the code! http://www.filedropper.com/xnabus
Please see below for the code from GameElements.cs. Hope this helps :). You could use any .Net Disassembler to do this. I used ILSpy and decompiled your code from XNA bus.exe file.
Note that, sometimes there could be minor issues with names of classes or methods. So, please go through the code once completely to ensure this.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
namespace XNA_bus
{
internal static class GameElements
{
public enum State
{
Menu,
Levels,
Level1,
Level2,
Level3,
Run,
Highscore,
Quit
}
private static Meny meny;
private static Levels levels;
private static Player player;
private static List<Fiender> Fiende;
private static List<GuldMynt> guldMynt;
private static List<Powerup> SuperSkepp;
private static List<Powerup> PenetratingBullets;
private static Texture2D guldMyntSprite;
private static Texture2D SuperskeppSprite;
private static Texture2D PenetratingbulletsSprite;
private static Utskrifter printText;
private static Bakgrund bakgrund;
private static Boss1 boss1;
private static int boss1Liv = 3;
private static int playerLiv = 1;
public static GameElements.State currentState;
public static void Initialize()
{
GameElements.guldMynt = new List<GuldMynt>();
GameElements.SuperSkepp = new List<Powerup>();
GameElements.PenetratingBullets = new List<Powerup>();
}
public static void LoadContent(ContentManager content, GameWindow window)
{
GameElements.player = new Player(content.Load<Texture2D>("Images/player/Player"), 0f, 200f, 2.5f, 4.5f, content.Load<Texture2D>("Images/player/bullet"));
GameElements.bakgrund = new Bakgrund(content.Load<Texture2D>("Images/bakgrund"), window);
GameElements.boss1 = new Boss1(content.Load<Texture2D>("Images/Enemies/Boss1"), 700f, 360f);
GameElements.meny = new Meny(0);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Start"), 1, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Highscore"), 6, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Avsluta"), 7, window);
GameElements.levels = new Levels(1);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 1"), 2, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 2"), 3, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 3"), 4, window);
GameElements.Fiende = new List<Fiender>();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
GameElements.printText = new Utskrifter(content.Load<SpriteFont>("Font1"));
GameElements.guldMyntSprite = content.Load<Texture2D>("Images/Powerups/SpelMynt");
GameElements.SuperskeppSprite = content.Load<Texture2D>("Images/Powerups/PowerUp");
GameElements.PenetratingbulletsSprite = content.Load<Texture2D>("Images/Powerups/PowerUp2");
}
public static GameElements.State MenyUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.meny.Update(gameTime);
}
public static void MenyDraw(SpriteBatch spriteBatch)
{
GameElements.bakgrund.Draw(spriteBatch);
GameElements.meny.Draw(spriteBatch);
}
public static GameElements.State RunUpdate(ContentManager content, GameWindow window, GameTime gameTime)
{
GameElements.bakgrund.Update(window);
GameElements.player.Update(window, gameTime);
foreach (Fiender f in GameElements.Fiende.ToList<Fiender>())
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (f.CheckCollision(b))
{
f.Liv = false;
GameElements.player.poäng++;
if (!GameElements.player.PenetratingBullets)
{
GameElements.player.AntSkott.Remove(b);
}
else if (GameElements.player.PenetratingBullets)
{
if (gameTime.get_TotalGameTime().TotalSeconds > GameElements.player.PenetratingBulletsTime + 2.0)
{
GameElements.player.PenetratingBullets = false;
}
}
}
}
if (f.Liv)
{
if (f.CheckCollision(GameElements.player))
{
GameElements.playerLiv--;
GameElements.player.Liv = false;
}
f.Update(window);
}
else
{
GameElements.Fiende.Remove(f);
}
if (!f.FKoll)
{
GameElements.Fiende.Remove(f);
GameElements.playerLiv--;
}
}
if (GameElements.boss1.Liv)
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (GameElements.boss1.CheckCollision(b))
{
GameElements.player.AntSkott.Remove(b);
GameElements.boss1Liv--;
}
}
GameElements.boss1.Update(window);
}
if (GameElements.boss1Liv == 0)
{
GameElements.boss1.Liv = false;
}
GameElements.State result;
if (!GameElements.boss1.Liv)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
Random random = new Random();
int newMynt = random.Next(1, 200);
if (newMynt == 1)
{
int rndX = random.Next(0, window.get_ClientBounds().Width - GameElements.guldMyntSprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - GameElements.guldMyntSprite.get_Height());
GameElements.guldMynt.Add(new GuldMynt(GameElements.guldMyntSprite, (float)rndX, (float)rndY));
}
foreach (GuldMynt gc in GameElements.guldMynt.ToList<GuldMynt>())
{
if (gc.Liv)
{
gc.Update(gameTime);
if (gc.CheckCollision(GameElements.player))
{
GameElements.guldMynt.Remove(gc);
GameElements.player.Poäng++;
}
}
else
{
GameElements.guldMynt.Remove(gc);
}
}
Random rnd = new Random();
int newPowerup = rnd.Next(1, 300);
if (newPowerup == 1)
{
int rndX = rnd.Next(0, window.get_ClientBounds().Width - GameElements.SuperskeppSprite.get_Width());
int rndY = rnd.Next(0, window.get_ClientBounds().Height - GameElements.SuperskeppSprite.get_Height());
GameElements.SuperSkepp.Add(new Powerup(GameElements.SuperskeppSprite, (float)rndX, (float)rndY));
}
foreach (Powerup Power in GameElements.SuperSkepp.ToList<Powerup>())
{
if (Power.Liv)
{
Power.Update(gameTime);
if (Power.CheckCollision(GameElements.player))
{
GameElements.SuperSkepp.Remove(Power);
GameElements.player.SuperSkepp = true;
GameElements.player.SuperSkeppTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.SuperSkepp.Remove(Power);
}
}
Random rnd2 = new Random();
int NewPowerup = rnd2.Next(1, 300);
if (NewPowerup == 1)
{
int rndX = rnd2.Next(0, window.get_ClientBounds().Width - GameElements.PenetratingbulletsSprite.get_Width());
int rndY = rnd2.Next(0, window.get_ClientBounds().Height - GameElements.PenetratingbulletsSprite.get_Height());
GameElements.PenetratingBullets.Add(new Powerup(GameElements.PenetratingbulletsSprite, (float)rndX, (float)rndY));
}
foreach (Powerup P in GameElements.PenetratingBullets.ToList<Powerup>())
{
if (P.Liv)
{
P.Update(gameTime);
if (P.CheckCollision(GameElements.player))
{
GameElements.PenetratingBullets.Remove(P);
GameElements.player.PenetratingBullets = true;
GameElements.player.PenetratingBulletsTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.PenetratingBullets.Remove(P);
}
}
if (!GameElements.player.Liv || GameElements.playerLiv == 0)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Run;
}
}
return result;
}
public static void RunDraw(SpriteBatch spriteBatch)
{
GameElements.boss1.Draw(spriteBatch);
GameElements.bakgrund.Draw(spriteBatch);
GameElements.player.Draw(spriteBatch);
foreach (Fiender f in GameElements.Fiende)
{
f.Draw(spriteBatch);
}
foreach (GuldMynt gc in GameElements.guldMynt)
{
gc.Draw(spriteBatch);
}
foreach (Powerup Power in GameElements.SuperSkepp)
{
Power.Draw(spriteBatch);
}
foreach (Powerup p in GameElements.PenetratingBullets)
{
p.Draw(spriteBatch);
}
GameElements.printText.Print("Points:" + GameElements.player.poäng, spriteBatch, 0, 0);
GameElements.printText.Print("Boss Liv:" + GameElements.boss1Liv, spriteBatch, 680, 0);
GameElements.printText.Print("Liv:" + GameElements.playerLiv, spriteBatch, 0, 20);
}
public static GameElements.State HighScoreUpdate()
{
GameElements.State result;
if (Keyboard.GetState().IsKeyDown(27))
{
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Highscore;
}
return result;
}
public static void HighScoreDraw(SpriteBatch spriteBatch)
{
}
private static void Reset(GameWindow window, ContentManager content)
{
GameElements.boss1Liv = 3;
GameElements.playerLiv = 1;
GameElements.boss1.Liv = true;
GameElements.player.Reset(0f, 200f, 2.5f, 4.5f);
GameElements.Fiende.Clear();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
}
public static GameElements.State LevelsUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.levels.Update(gameTime);
}
public static void LevelsDraw(SpriteBatch spritebatch)
{
GameElements.bakgrund.Draw(spritebatch);
GameElements.levels.Draw(spritebatch);
}
}
}
I am working on a project using .Net Compact Framework 3.5 using C# 3.0.
I have a user control which receives data every 15 miliseconds and I have to draw shapes
like lines, rectangle, filled rectangles on user control.
I want to know what is the fastest way to draw these shapes, I am also open to use P/Invoke methods if there are some to increase performance and speed.
The code I am using is as follows:
private void DrawThreeFunctions(Graphics g)
{
// drawing back functions
if (DisplayFunction1.DrawOrder == DrawOrder.Back && GraphDataArray.Length > 0)
{
DrawFunction(g, DisplayFunction1, GraphDataArray[0]);
}
if (DisplayFunction2.DrawOrder == DrawOrder.Back && GraphDataArray.Length > 1)
{
DrawFunction(g, DisplayFunction2, GraphDataArray[1]);
}
if (DisplayFunction3.DrawOrder == DrawOrder.Back && GraphDataArray.Length > 2)
{
DrawFunction(g, DisplayFunction3, GraphDataArray[2]);
}
// drawing middle functions
if (DisplayFunction1.DrawOrder == DrawOrder.Middle && GraphDataArray.Length > 0)
{
DrawFunction(g, DisplayFunction1, GraphDataArray[0]);
}
if (DisplayFunction2.DrawOrder == DrawOrder.Middle && GraphDataArray.Length > 1)
{
DrawFunction(g, DisplayFunction2, GraphDataArray[1]);
}
if (DisplayFunction3.DrawOrder == DrawOrder.Middle && GraphDataArray.Length > 2)
{
DrawFunction(g, DisplayFunction3, GraphDataArray[2]);
}
// drawing front functions
if (DisplayFunction1.DrawOrder == DrawOrder.Front && GraphDataArray.Length > 0)
{
DrawFunction(g, DisplayFunction1, GraphDataArray[0]);
}
if (DisplayFunction2.DrawOrder == DrawOrder.Front && GraphDataArray.Length > 1)
{
DrawFunction(g, DisplayFunction2, GraphDataArray[1]);
}
if (DisplayFunction3.DrawOrder == DrawOrder.Front && GraphDataArray.Length > 2)
{
DrawFunction(g, DisplayFunction3, GraphDataArray[2]);
}
}
private void DrawFunction(Graphics g, DisplayFunction function, int[] data)
{
Color color = Utils.GetColor(function.Color);
switch (function.Shape)
{
case FunctionShape.StepLine:
DrawStepLines(g, data, color);
break;
case FunctionShape.Rectangle:
DrawFilledRectangles(g, data, color);
break;
case FunctionShape.FramedRectangle:
DrawFramedRectangles(g, data, color);
break;
case FunctionShape.Line:
DrawLines(g, data, color);
break;
default:
break;
}
}
#region Drawing methods
// drawing lines
private void DrawLines(Graphics g, int[] lineData, Color lineColor)
{
BarPositions = new List<int>();
List<Point> linePoints = new List<Point>();
int lineYPos = -1;
int lineXPos = FirstBarDrawPosition;
Point point = Point.Empty;
using (Pen linePen = new Pen(lineColor, 2.0f))
{
for (int i = FirstVisibleItemIndex, k = 0; i < _indexLimit; i++, k++)
{
if (base.GetBarEndPosition(k) > Width)
break;
lineXPos = GetTickPosition(k);
BarPositions.Add(lineXPos);
if (i < lineData.Length)
lineYPos = lineData[i];
else
continue;
point.X = lineXPos;
point.Y = lineYPos;
linePoints.Add(point);
}
if (linePoints.Any())
{
g.DrawLines(linePen, linePoints.ToArray());
}
}
}
// drawing framed rectangles
private void DrawFramedRectangles(Graphics g, int[] functionValues, Color functionColor)
{
BarPositions = new List<int>();
int barXPos = FirstBarDrawPosition;
Rectangle barRect = Rectangle.Empty;
barRect.Width = WidthOfBar - 1;
int barYPos = -1;
using (Pen barPen = new Pen(functionColor))
{
for (int i = FirstVisibleItemIndex, k = 0; i < _indexLimit; i++, k++)
{
if (base.GetBarEndPosition(k) > Width)
return;
BarPositions.Add(GetTickPosition(k));
if (i < functionValues.Length)
barYPos = functionValues[i];
else
continue;
//barRect = new Rectangle();
barRect.X = barXPos;
barRect.Y = barYPos;
//barRect.Width = WidthOfBar - 1;
barRect.Height = Height - barYPos;
g.DrawRectangle(barPen, barRect);
barXPos += (WidthOfBar + DistanceBetweenBars);
}
}
}
// drawing filled rectangles
private void DrawFilledRectangles(Graphics g, int[] functionValues, Color functionColor)
{
BarPositions = new List<int>();
int barXPos = FirstBarDrawPosition;
Rectangle barRect = Rectangle.Empty;
barRect.Width = WidthOfBar;
int barYPos = -1;
using (SolidBrush barBrush = new SolidBrush(functionColor))
{
for (int i = FirstVisibleItemIndex, k = 0; i < _indexLimit; i++, k++)
{
if (base.GetBarEndPosition(k) > Width)
return;
BarPositions.Add(GetTickPosition(k));
if (i < functionValues.Length)
barYPos = functionValues[i];
else
continue;
//barRect = new Rectangle();
barRect.X = barXPos;
barRect.Y = barYPos;
//barRect.Width = WidthOfBar;
barRect.Height = Height - barYPos;
g.FillRectangle(barBrush, barRect);
barXPos += (WidthOfBar + DistanceBetweenBars);
}
}
}
private void DrawStepLines(Graphics g, int[] lineData, Color lineColor)
{
BarPositions = new List<int>();
int lineYPos = -1;
int barXPos = FirstBarDrawPosition;
using (Pen linePen = new Pen(lineColor, 2.0f))
{
for (int i = FirstVisibleItemIndex, k = 0; i < _indexLimit; i++, k++)
{
if (base.GetBarEndPosition(k) > Width)
return;
BarPositions.Add(GetTickPosition(k));
if (i < lineData.Length)
lineYPos = lineData[i];
else
continue;
// draw third function line
//lineHeight = lineData[i];
g.DrawLine(linePen, barXPos, lineYPos, barXPos + WidthOfBar - 1, lineYPos);
barXPos += (WidthOfBar + DistanceBetweenBars);
}
}
}
I am using drawing order and shape like step line , line , framed rectangle ( just rectangle ) and rectangle is filled rectangle.
Because of performance critical application I want to know the fastest way of drawing these shapes.
Thanks in advance for any suggestion.
Are you familiar with double-buffering? Keep an offscreen image buffer to do your writes to as the changes come in. Then override the OnPaint to blit the whole image in one statement. Also, override the OnPaintBackground with a no-op to get rid of the default behavior of clearing the control to its backcolor on each paint.
Old as the hills, but here is an article on some best-practices on using GDI in the Compact Framework.