How to get an Image from Harddrive into an Bufferdimage in java - graphics2d

currently me and some other people of my team are trying to build a navigational Application for a studentsproject. we are working with the JXMapKit, and want to set an other randerer for the waypoints on the map, therefore a methode is needed which useses Graphics2D to display image(i at least i belief the methode does that with this Object). So this is the Problem: how can i get an normal Image from my Harddrive into this Graphics2D Object? I read something about that i need a Bufferedimage but that didn't helped me much.
I someone gets the Point in what i mean, because me english is, friendly spoken not the best^^
neverless, i hope someone can help me with this problem

You can use ImageIO.read() like this:
String pathToMyFile = "C:\image.jpg";
BufferedImage image = ImageIO.read(new File(pathToMyImageFile));
Returns a BufferedImage as the result of decoding a supplied File with an ImageReader chosen automatically from among those currently registered. The File is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.
Then you can use the drawImage() function of your Graphics2D object:
int x,y = 10; //the coorinates where to draw the image
graphics2D.drawImage(image, x, y, null)

Related

(AS3) MovieClip' s motion path as Shape on stage

I'm making a game for a school project. The concept is pretty simple, you need to fix the circuit wires(the path in the form of rectangular shapes) so that electricity can run through the circuit and light up the bulbs.
I'm trying to find a way on how you can make a movie clip travel the wires. I have seen a lot of tutorials where they state coordinates and angles for the motion path but I want to make it so that the movie clip will automatically follow the shape path present on the stage so even if the path changes(for different levels), the movie clip will still follow that path. As of the moment, all I can do is create a predefined guide path inside the movie clip which traces the path.
Follow-up question:
Is there also a way on how I can detect if the shape path is complete or not? The system will check whether or not the wires are connected to each other.
You should instead do a metadata calculation prior to moving something you intend, this way you first calculate whether your puzzle is solved, once it is, or once you have determined the point where your movable object should stop and display the error, you then make a path out of simple sections, then make your object move by them one by one until final point, then display the outcome. This is the general idea. A simple code of moving an object by sections looks like this:
var sections:Vector.<Point>; // we need x&y sequence. Fill this prior to launching the routine
var position:int=0; // where are we now
var velocity:int=8; // pixels per frame, adjust as needed
movable.addEventListener(Event.ENTER_FRAME,moveABit);
function moveABit(e:Event):void {
var nextPoint:Point=sections[position];
var do:DisplayObject=e.target as DisplayObject; // what we are moving
var here:Point=new Point(do.x,do.y);
if (Point.distance(here,nextPoint)<velocity) {
// this means we are too close to interpolate, just place
do.x=nextPoint.x;
do.y=nextPoint.y;
position++;
if (position>=sections.length) {
// movement finished
// TODO make your final animation
do.removeEventListener(Event.ENTER_FRAME,moveABit); // stop moving
}
} else {
// interpolate movement
var angle:Number=Math.atan2(nextPoint.y-here.y,nextPoint.x-here.x);
do.x+=Math.cos(angle)*velocity;
do.y+=Math.sin(angle)*velocity;
// if the object will move to wrong direction, fix this code!
}
}
If you want to see if your 'shape' is complete:
You can create a vector of boolean variables(every variable indicate a node of your wires- you set the variable to true when is connected), and you need a function to check if all the vars from vector are true (with loop), that means your shape is complete. Hope this idea helps!

Corona use object properties from Tiled layers

I am new to Lua scripting, and game development. So please I am just a noob in Lua.
I have searched the net for solutions to my problems, without any luck.
I use Photoshop, Corona, Dusk, json and Tiled on windows7.
I am creating a "board" like game, i.e. Setlers. I am using a world map, as the background. The background image of the game area is a world map (world.png file). I have no problem here.
I would like to create transparrent clickable objects matching the countrys borders on my gamemap with all parameters and values (I have added in Tiled) stored in the object. So When the player clicks on the country the transparrent object (on top of the map) is the one clicked and an eventlistener acts on the click.
In Tiled I can create all the objects I need, naming them + assigning parameters and other values.
If I add object.alpha value in Tiled, the alpha value is passed on to corona and working there.
How can I read these data from the json/tmx file in Corona and adding them to a lua table?
The way I am thinking to use the Tiled map and its objects, is to create one polyline trace of each country’s border (creating one object per country). Then place each “country traced object” on top of the world.png map, also naming the object with the countrys name like “object.name = TileBritannia” and also the other properties for use in game.
My problem is getting the objects info, like object.name, and an eventlistener reacting to a click on the object.
Is a polyline the right way to create a clickable area on a map, when I use a png file as a background image?
What is the best way to create a country border objects, in one layer or with all countries as individual object layers in Tiled.
Can I create one layer with sub objects and still access them in my code?
How do I get the object name and other properties, set in Tiled.
When I try to use the (local britannia = tiledMap:load("britannia.json")) the "load" is not working, getting a nil value.
I am looking for a code that will extract/get/read the object.name i.e. “objBritannia” or "TileBritannia". from the json/tmx file.
When I try to read the different parameters from the json file, I don't get the result I expect. I get the result = function: 046A73B0, was hoping for an object name of some sort.
Please provide links to or code example.
I have edited the question.
Thanks
For questions 1 and 2: I have not used Tiled, but based on Corona Tiled, you have the right strategy in mind. That page makes me think that you can just use tap event listener to detect tap. If you are having issues with the example on that web page, please update your question to be more specific. If tap event handling doesn't work (maybe you're talking about a different Tiled lib), look a Polygon fill and Point in Polygon detection, because that's basically what you need to do. Try some stuff from there. If it still doesn't work for you, then update your question with specifics otherwise it will be likely get closed (it is a little too broad as it is).
For #3, Lua is a dynamic language that supports adding properties to objects in one line. So upon the example on the Corona Tiled page, all you would have to do is
tiledMap = require("tiled")
local britannia = tiledMap:load("britannia.json")
britannia.name = "Britannnia"
local Zulu = tiledMap:load("zulu.json")
zulu.name = "zulu"
Naturally you will probably have a whole bunch so you will create a function that you call for each tile. It's not clear what map.layer["objBritannia "].nameIs("TileBritannia") is supposed to do so I can't comment.

Practical way of getting a picture of a library object

I´m making a level creator for my platformer game on AS3. I´m looking for a way of getting a graphical representation of a library object on my .fla, so the user can insert that object on the world on the desired coordinate. What I mean with this is that I just want a picture of the first frame of the mc, without taking its properties and methods (without the need to make a .jpg containing that image), because that´s when problems begin to appear, and I just want the object functionality on play mode, not the level creator.
Let´s say, for example, a ball that bounces all the time by updating its location every frame. On the level creator I just want to get the ball picture to insert it on the desired location. If I take the whole ball object to the level creator it won´t stop bouncing and it will mess things up.
I hope I´m clear... I just want to know if there is a practical solution to this; if not then I´ll make a class where all the world objects would extend to, that has a init() function that initializes all the object functionality, so it´s called only on play mode and not on level creator. Thanks for reading anyway.
What you're doing wrong is adding functionality directly to the MovieClip.
Please read one of my previous answers that covers this concept in more depth.
MovieClips should be used for the display only, representing the graphics of an actual game class, for example:
public class Player
{
// Graphics that represent the Player.
protected var display:MovieClip;
// Constructor.
public function Player()
{
display = new PlayerMovieClip();
}
}
Anyways, once you fix that you can take a Bitmap sample of MovieClips using BitmapData and its draw():
// Assume that 'mc' is your MovieClip.
var sample:BitmapData = new BitmapData(mc.width, mc.height, true, 0);
sample.draw(mc);
// This is your image.
var texture:Bitmap = new Bitmap(sample);

Trying to convert openGL to MFC coordinates and having Problems with "gluProject"

To clarify things, what i am trying to do is to get the openGL coordinates and manipulate them in my mfc code. not to get an openGL object. i'm using the mfc to control the position of the objects in the openGL.
Hi, i'm trying to find the naswer on the web and can't find a full solution that i can use and that will work...
I'm developing a MFC project with static picture as the canvas for an openGL class that draw the grphics for my game.
On moush down, i need to retrive a shape coordinate from the openGL class.
I'm looking for a way to convert the openGL coordinates to MFC coordinates but no matter what i try i get junk after using the gluProject or gluUnProject (i've tried to do both ways but non is working)
GLdouble modelMatrix[16];
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
GLdouble projMatrix[16];
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
int viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
POINT mouse; // Stores The X And Y Coords For The Current Mouse Position
GetCursorPos(&mouse); // Gets The Current Cursor Coordinates (Mouse Coordinates)
ScreenToClient(hWnd, &mouse);
GLdouble winX, winY, winZ; // Holds Our X, Y and Z Coordinates
winX; = (float)point.x; // Holds The Mouse X Coordinate
winY; = (float)point.y; // Holds The Mouse Y Coordinate
winY = (float)viewport[3] - winY;
glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
GLdouble posX=s1->getPosX(), posY=s1->getPosY(), posZ=s1->getPosZ(); // Hold The Final Values
gluUnProject( winX, winY, winZ, modelMatrix, projMatrix, viewport, &posX, &posY, &posZ);
gluProject(posX, posY, posZ, modelMatrix, projMatrix, viewport, &winX, &winY, &winZ);
This is just part of the code i've tried. ofcourse not gluProject and gluUnProject together. just had them both here to show.....and i know there is lots of junk over there, its from some of my tries...
p.s. i've tried many many more combinations and examples from the web and nothing seem to work in my case....
Can any one show me what is the right way to do the transformation?
10x
It looks like you're trying to retrieve the object (or objects) that is/are at a particular point. If this is the case, gluProject and/or gluUnProject isn't really a very suitable tool for the task. OpenGL has a selection mode intended specifically for this kind of task.
In typical use, you specify a small square (e.g., 5x5 pixels) around the mouse click spot with gluPickMatrix, set selection mode with glRenderMode, set a buffer with glSwelectBuffer, and then draw your scene. The drawing doesn't go to the screen, but fills the buffer you specified wiyh records of what was drawn within the specified area.

Actionscript 3 pixel perfect collision. How to? (learning purposes)

I know that there are people out there creating classes for this (ie http://coreyoneil.com/portfolio/index.php?project=5). But I want to learn how to do it myself so I can create everything I need the way I need.
I've read about BitMap and BitMapData. I should be able to .draw the MovieClips onto a BitMap so I could then cycle the pixels looking for the collisions. However, It's weird and confusing dealing with the offsets.. And it seams like the MyBitMap.rect has always x = 0 and y = 0... and I can't seam to find the original position of the things...
I'm thinking of doing a hitTestObject first, then if this was positive, I would investigate the intersection betwen the movieclips rectangles for the pixel collisions.
But then there is also another problem (the rotation of movieclips)...
...I need some enlightment here on how to do it.
Please, any help would be appreciated..
If you're using BitmapData objects with transparency you can use BitmapData.hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean.
You'll have to change from global coords to the local BitmapData coords which will require a bit of math if it is rotated. That's easily achieved (look up affine transform for more info on wiki):
var coordTransform:Matrix = new Matrix();
coordTransform.rotate(rotationRadians);
coordTransform.translate(x, y);
coordTransform.transformPoint(/* your point */);
A classic reference for pixel perfect collision detection in flash is this Grant Skinner's article. It's AS2, but the logic is the same for AS3 (there are ports available if you google a bit).
If I recall correctly, this particular implementation worked as long as both tested objects had the same parent, but that can be fixed.
About BitmapData x and y values, I understand it could be confusing; however, the way it works makes sense to me. A BitmapData is just what the name implies: pixel data. It's not a display object, and cannot be in the display list; so having x or y different than 0 doesn't really make sense, if you think about it. The easiest way to deal with this is probably storing the (x,y) offset of the source object (the display object you have drawn from) and translate it to the global coordinate space so you can compare any objects, no matter what's their position in the display list (using something like var globalPoint:Point = source.parent.localToGlobal(new Point(source.x,source.y)).
I've previously used Troy Gilbert's pixel perfect collision detection class (adapted from Andre Michelle, Grant Skinner and Boulevart) which works really well (handles rotation, different parents, etc.):
http://troygilbert.com/2007/06/pixel-perfect-collision-detection-in-actionscript3/
http://troygilbert.com/2009/08/pixel-perfect-collision-detection-revisited/
and from there he has also linked to this project (which I've not used, but looks really impressive):
http://www.coreyoneil.com/portfolio/index.php?project=5
I managed to do it after all, and I already wrote my class for collision detections,/collisions angle and other extras.
The most confusing process is maybe to align the bitmaps correctly for comparing. When whe draw() a movieclip into a a BitmapData, if we addChild() the corresponding Bitmap we can see that part of it is not visible. it appears to be drawn from the center to right and down only, leaving the top and left parts away from beeing drawn. The solution is giving a transform matrix in the second argument of the draw method that aligns the bitmap and makes it all be drawn.
this is an example of a function in my class to create a bitmap for comparing:
static public function createAlignedBitmap(mc: MovieClip, mc_rect: Rectangle): BitmapData{
var mc_offset: Matrix;
var mc_bmd: BitmapData;
mc_offset = mc.transform.matrix;
mc_offset.tx = mc.x - mc_rect.x;
mc_offset.ty = mc.y - mc_rect.y;
mc_bmd = new BitmapData(mc_rect.width, mc_rect.height, true, 0);
mc_bmd.draw(mc, mc_offset);
return mc_bmd;
}
in order to use it, if you are on the timeline, you do:
className.createAlignedBitmap(myMovieClip, myMovieClip.getBounds(this))
Notice the use of getBounds which return the rectangle in which the movie clip is embedded. This allows the calculation of the offset matrix.
This method is quite similar to the on shown here http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
By the ways, if this is an interesting matter for you, check my other question which I'll post in a few moments.