Unity: Getting the pixel on an image based on the location of buttons above the image - image

For my 2D Game; I have a panel with an image Component (with a sprite) and a GridLayout component.
On the panel i have also put a script that creates buttons for the panel (as children)
public void InitializeGrid(int rows, int columns, List<RbzFilteredWord> words)
{
RectTransform myRect = GetComponent<RectTransform>();
buttonHeight = myRect.rect.height / (float)rows;
buttonWidth = myRect.rect.width / (float)columns;
GridLayoutGroup grid = this.GetComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(buttonWidth, buttonHeight);
...
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
button = (Button)Instantiate(prefab);
button.transform.SetParent(transform, false);
...
}
Problem:
The text of each button must indicate the color of the pixel (from the underlying image) at the pivot location of that button
I know that this method is available: GetPixel(x,y), but i don't know which coordinates i need to use as parameters for this method, since i'm a noob at unity

x and y are the position indexes in the pixels bidimensional array of teh texture.
That is:
x goes from 0 to the width - 1 of the texture image (in pixels)
y goes from 0 to the height - 1 of the texture image (in pixels)

Related

Creating Grid in as3

I am trying to make to grid to squares using as3.
I am using nested for loops to create the grid.
import flash.display.Shape;
import flash.display.MovieClip;
var n=10;
var myClip = new MovieClip;
stage.addChild(myClip);
for (var i = 0; i < n * 10; i += 10) {
for (var j = 0; j < n * 10; j += 10) {
var _shape = new Shape;
myClip.addChild(_shape);
_shape.graphics.lineStyle(1);
_shape.graphics.beginFill(0xcccccc);
_shape.graphics.drawRect(i, j, 10, 10);
_shape.graphics.endFill();
}
}
I am applying Zooming and Panning Gestures on myClip. For this Grid size everything works fine. As soon as I increase the value of n, it starts lagging
My game requires a bigger grid. Please help
I'll show some ideas as code, my AS3 is a bit rusty but perhaps it helps.
You can reduce the number of Shape instances or draw the vector based grid graphic to a Bitmap. Since you are zooming and panning it you'll want to smooth it. Depending on performance and how much you zoom you also may want to draw the bitmap at a higher resolution than initially used. See comments in the below.
import flash.display.Shape;
import flash.display.MovieClip;
var n=10;
// do you actually need dynamic binding or a timeline in this?
// if not (also if you don't know what it means) do use the Sprite class instead
var myClip = new MovieClip;
stage.addChild(myClip);
// if you don't need individual shapes move this out of the for loop
// your logic with all of the shapes having the same origin suggests this might be so
var _shape = new Shape;
myClip.addChild(_shape);
for (var i = 0; i < n * 10; i += 10) {
for (var j = 0; j < n * 10; j += 10) {
_shape.graphics.lineStyle(1);
_shape.graphics.beginFill(0xcccccc);
_shape.graphics.drawRect(i, j, 10, 10);
_shape.graphics.endFill();
}
}
// then we can draw the grid to a bitmap
// since you are scaling it I'm drawing it a 300% resolution
var _bmd:BitmapData = new BitmapData(_shape.width*3, _shape.height*3, true, 0);
var _bit:Bitmap = new Bitmap(_bmd);
myClip.addChild(_bit);
_shape.width*=3;
_shape.height*=3;
_bmd.draw(stage);
_bit.smoothing = true;
_bit.width/=3;
_bit.height/=3;
// and remove the vector shape so it won't be rendered
myClip.removeChild(_shape);
// if need be it can be redrawn later

Zooming into canvas via js causes content to be lost?

http://deepschool.kd.io/Pages/Experiments/draw.htm
This is a Image editor I am working on, But it has a bug. Let's say you have created an image a 15x Zoom, when you change the zoom, the image is lost. Why is this? and what is the Remedy?
HTML:
Zoom:
<input type="number" id="zoom" min="1" max="50" onchange="zoomy()">
JS:
var zoomy = function() {
var zoomamount = zoom.value
var canvassize = zoomamount * 16
c.width = canvassize
c.height = canvassize
};
Thanks In Advance
If you want to zoom into canvas, it means you have to redraw it with zoom.
So instead of drawing pixels on click right onto canvas, which is made of pure pixels... You need to first create some representation of your grid of pixels.
var gridOfPixels = [];
Let's say you are ok with static size for now. Make it 8x8 pixels. At start you want to initialize your array:
for (var i=0; i < 8*8; i++) gridOfPixels[i] = 0;
So the grid canvas is ready, now we need to draw it.
function renderGrid() {
for (var y=0; y < 8; y++)
for (var x=0; x < 8; x++)
renderPixel( x, y, gridOfPixels[x+y*8] );
}
You already know how to renderPixel - calculate the rectangle position (posX = x*pixWidth, posY*pixHeight), where pixWidth is canvasWidth/8, etc.. Now you draw all your pixels, using the third parameter for the color.
To finish, you have to connect onclick to put a pixel on grid, and then call renderGrid so the user sees the change.
$('#my-canvas').click(function(e) {
var x = ...;
var y = ...; // calculate the position of pixels from mouse position inside canvas
// dont forget to check that x,y are in the 0-7 range
// dont forget to convert x,y to whole number using parseInt()
gridOfPixels[x+y*8] = 1;
renderGrid(); // update the grid canvas
});
Now, every time you resize the canvas or change some variables, the original canvas content will be saved in your grid, and you can renderGrid() any time you need to. You could even do it in realtime, animating the color of the pixels, etc..
Have fun. :)

How do I get a random number to stay fixed with slick?

I'm a beginner in Java as well as with the slick tools. I want to make a game that has different coloured cubes randomly placed within a certain area of the window.
I use two for-loops and call for a random number in render. I get the cubes placed exactly as I want, but the problems is that they flicker in all colours. I guess it has to do with how I call for a random number and that it gets updated with FPS?!
Please help me!!
public void render(GameContainer gc, StateBasedGame sdg, Graphics g) throws SlickException {
//set background
Image background = (new Image("res/background.png")).getScaledCopy(800, 500);
g.drawImage(background, 0, 0);
//set gamescape
blue = (new Image("res/blue.png")).getScaledCopy(20,20);
green = (new Image("res/green.png")).getScaledCopy(20,20);
red = (new Image("res/red.png")).getScaledCopy(20,20);
int xvalue = 300;
int yvalue = 400;
for (int a = 1; a < 20; a++) {
for (int i = 1; i < 10; i++) {
r = rand.nextInt(3);
if(r==0){g.drawImage(blue,xvalue,yvalue);}
else if(r==1){g.drawImage(red, xvalue, yvalue);}
else{g.drawImage(green, xvalue, yvalue);}
xvalue = xvalue+20;
}
yvalue = yvalue - 20;
xvalue = xvalue -180;
}
}
Your problem is that you generate a new random number each time you redraw the scene.
To resolve this, you may have to create an array in which you store the generated color of each cube. And each time you redraw your images, you just read each color value in the array.

Pixel reordering is wrong when trying to process and display image copy with lower res

I'm currently making an application using processing intended to take an image and apply 8bit style processing to it: that is to make it look pixelated. To do this it has a method that take a style and window size as parameters (style is the shape in which the window is to be displayed - rect, ellipse, cross etc, and window size is a number between 1-10 squared) - to produce results similar to the iphone app pxl ( http://itunes.apple.com/us/app/pxl./id499620829?mt=8 ). This method then counts through the image's pixels, window by window averages the colour of the window and displays a rect(or which every shape/style chosen) at the equivalent space on the other side of the sketch window (the sketch when run is supposed to display the original image on the left mirror it with the processed version on the right).
The problem Im having is when drawing the averaged colour rects, the order in which they display becomes skewed..
Although the results are rather amusing, they are not what I want. Here the code:
//=========================================================
// GLOBAL VARIABLES
//=========================================================
PImage img;
public int avR, avG, avB;
private final int BLOCKS = 0, DOTS = 1, VERTICAL_CROSSES = 2, HORIZONTAL_CROSSES = 3;
public sRGB styleColour;
//=========================================================
// METHODS FOR AVERAGING WINDOW COLOURS, CREATING AN
// 8 BIT REPRESENTATION OF THE IMAGE AND LOADING AN
// IMAGE
//=========================================================
public sRGB averageWindowColour(color [] c){
// RGB Variables
float r = 0;
float g = 0;
float b = 0;
// Iterator
int i = 0;
int sizeOfWindow = c.length;
// Count through the window's pixels, store the
// red, green and blue values in the RGB variables
// and sum them into the average variables
for(i = 0; i < c.length; i++){
r = red (c[i]);
g = green(c[i]);
b = blue (c[i]);
avR += r;
avG += g;
avB += b;
}
// Divide the sum of the red, green and blue
// values by the number of pixels in the window
// to obtain the average
avR = avR / sizeOfWindow;
avG = avG / sizeOfWindow;
avB = avB / sizeOfWindow;
// Return the colour
return new sRGB(avR,avG,avB);
}
public void eightBitIT(int style, int windowSize){
img.loadPixels();
for(int wx = 0; wx < img.width; wx += (sqrt(windowSize))){
for(int wy = 0; wy < img.height; wy += (sqrt(windowSize))){
color [] tempCols = new color[windowSize];
int i = 0;
for(int x = 0; x < (sqrt(windowSize)); x ++){
for(int y = 0; y < (sqrt(windowSize)); y ++){
int loc = (wx+x) + (y+wy)*(img.width-windowSize);
tempCols[i] = img.pixels[loc];
// println("Window loc X: "+(wx+(img.width+5))+" Window loc Y: "+(wy+5)+" Window pix X: "+x+" Window Pix Y: "+y);
i++;
}
}
//this is ment to be in a switch test (0 = rect, 1 ellipse etc)
styleColour = new sRGB(averageWindowColour(tempCols));
//println("R: "+ red(styleColour.returnColourScaled())+" G: "+green(styleColour.returnColourScaled())+" B: "+blue(styleColour.returnColourScaled()));
rectMode(CORNER);
noStroke();
fill(styleColour.returnColourScaled());
//println("Rect Loc X: "+(wx+(img.width+5))+" Y: "+(wy+5));
ellipse(wx+(img.width+5),wy+5,sqrt(windowSize),sqrt(windowSize));
}
}
}
public PImage load(String s){
PImage temp = loadImage(s);
temp.resize(600,470);
return temp;
}
void setup(){
background(0);
// Load the image and set size of screen to its size*2 + the borders
// and display the image.
img = loadImage("oscilloscope.jpg");
size(img.width*2+15,(img.height+10));
frameRate(25);
image(img,5,5);
// Draw the borders
strokeWeight(5);
stroke(255);
rectMode(CORNERS);
noFill();
rect(2.5,2.5,img.width+3,height-3);
rect(img.width+2.5,2.5,width-3,height-3);
stroke(255,0,0);
strokeWeight(1);
rect(5,5,9,9); //window example
// process the image
eightBitIT(BLOCKS, 16);
}
void draw(){
//eightBitIT(BLOCKS, 4);
//println("X: "+mouseX+" Y: "+mouseY);
}
This has been bugging me for a while now as I can't see where in my code im offsetting the coordinates so they display like this. I know its probably something very trivial but I can seem to work it out. If anyone can spot why this skewed reordering is happening i would be much obliged as i have quite a lot of other ideas i want to implement and this is holding me back...
Thanks,

I want to draw a grid on the Windows Phone 7 using XNA

I am trying to draw a grid on the screen of a Windows Phone; it will help me better position my sprites on the screen rather than guessing locations on the screen.
I have found several examples of a grid (2d or 3d) using XNA 3.0, but unfortunately the architectures are different and so the code doesnt work in XNA 4.0
Does anyone have something that could work?
Thanks!
You can download a PrimitiveBatch class here http://create.msdn.com/en-US/education/catalog/sample/primitives and use the code below to generate an appropriate grid as a texture.
PrimitiveBatch primitiveBatch;
private Texture2D GenerateGrid(Rectangle destRect, int cols, int rows, Color gridColor, int cellSize)
{
int w = (int)(cols * gridCellSize);
int h = (int)(rows * gridCellSize);
float uselessWidth = destRect.Width - w;
float uselessHeigth = destRect.Height - h;
Rectangle bounds = new Rectangle((int)(uselessWidth / 2) + destRect.X, (int)(uselessHeigth / 2) + destRect.Y, w, h);
RenderTarget2D grid = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
GraphicsDevice.SetRenderTarget(grid);
GraphicsDevice.Clear(Color.Transparent);
primitiveBatch.Begin(PrimitiveType.LineList);
float x = bounds.X;
float y = bounds.Y;
for (int col = 0; col < cols + 1; col++)
{
primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Top), gridColor);
primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Bottom), gridColor);
}
for (int row = 0; row < rows + 1; row++)
{
primitiveBatch.AddVertex(new Vector2(bounds.Left, y + (row * gridCellSize)), gridColor);
primitiveBatch.AddVertex(new Vector2(bounds.Right, y + (row * gridCellSize)), gridColor);
}
primitiveBatch.End();
GraphicsDevice.SetRenderTarget(null);
return grid;
}
One quick and dirty way you can do it (as it is for debugging the quicker the better) is to simply create a texture of a grid that is of the same resolution you are running your XNA game at (if you are running it at the same resolution as the phone, this will be 480x800). Most of the texture will simply be an alpha map and with grid lines of one pixel, you could create multiple resolutions or you can repeat a small texture of a single pixel cross dividing a section of the screen that is divisible by the resolution you are running at.
The draw method will be something as below and be called everyframe.
This code can declared inside your game class
Texture2D gridTexture;
Rectangle gridRectangle;
This code should be in your LoadContent method
//Best to use something like a png file
gridTexture = content.Load<Texture2D>("pathto/mygridtexture");
gridRectangle = new Rectangle(0,0,resolutionX,resolutionY);
This method should be called from your Draw method last to ensure it is on top assuming you are just using the standard spriteBatch.Begin() to render sprites (first if you are doing FrontToBack rendering).
public void DrawGrid()
{
spriteBatch.Draw(gridTexture, gridRectangle, Color.White);
}
This grid will remain stationary throughout the running of your application and should be useful when trying to line up your UI or objects that have relative positions in your game.
HTH.
You may want to take a look at the XPF project by RedBadger. It enables you to use XAML style layout in an XNA project.

Resources