flipping sprite image in Android game - java

I am making a game in Android that requires a list of sprites to running from right to left so I try to flip the image using the code below.
It slows the game speed down so much, moves fast running to the right but slows down so much running to the left.
public void Draw(Canvas spriteBatch, int X, int Y, int imageIndex,int flip)
{
int drawY = (imageIndex / columns);
int drawX = imageIndex - drawY * columns;
int spriteX = drawX * spriteWidth;
int spriteY = drawY * spriteHeight;
Rect src = new Rect( spriteX, spriteY,spriteX + spriteWidth, spriteY + spriteHeight);
Rect dst = new Rect(X, Y, X + spriteWidth,Y + spriteHeight);
location.X = X;
location.Y = Y;
if(flip == 1)
{
//here image is flipped
spriteBatch.save();
spriteBatch.scale(-scaleX, scaleY, X, Y);
spriteBatch.drawBitmap(texture2D,src,dst, paint);
spriteBatch.restore();
//Use simple use this to flip image canvas.scale(-1, 1)
}
else if(flip == 0)
{
//draws sprite without flipping
spriteBatch.save();
spriteBatch.scale(scaleX, scaleY, X, Y);
spriteBatch.drawBitmap(texture2D,src,dst, paint);
spriteBatch.restore();
}
this.SetFrame(imageIndex);
}
I can flip using matrix but I can't draw a sprite using matrix.
Is there a way to draw sprite using matrix and would it make it faster?
matrix.reset();
matrix.setTranslate(location.X, location.Y);
matrix.setScale(-scaleX,scaleX);
matrix.postTranslate(location.X + texture2D.getWidth(), location.Y);
Or is there another way that is faster?

So I think that the matrix solution should will work perfectly the canvas object includes it's own built in matrix which if you manipulate will affect the output of all graphics after that point. So you just set the matrxi and then do the draw.
You're solution is okay but you're doing it wrong - rather do this part ONCE:
Create the left-ward facing sprite as you do at the beginning and then store it. Then EACH FRAME: Use this 'cached' copy of the inverted bitmap that you created.
A third solution (which I haven't tried but might work) is to manipulate the destination rectangle so that the left and right edges are swapped - the canvas docs say, "Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle." - I suspect that this might include negative scaling to fit the space where the right edge is smaller than the left although the docs do not explicitly say so.

Related

LibGDX: Sprite.setBounds doesn't work correctly with volatile coordinates and InputAdapter

Faced a problem while trying to handle clicking on a moving image.
I used InputAdapter.touchDown() to handle the click and created Sprite for the image. Then I set the borders through Sprite.setBounds(). Further, in fact, the problem: if the coordinates in setBounds() are unchanged - the click is handled correctly. But if you change them (position.x++, for example) - the object comes into motion, but clicks are not read.
I can’t understand where the reason.
I tried to make a alterable variable outside the method, but this also didn't bring any result.
I tried using batch.draw(img) instead of img.draw(batch) - the effect is the same.
I tried to relocate Gdx.input.setInputProcessor() to the render() method, after img.setBounds() - nothing changed.
I even compared the coordinates of the Img and the Bounds area online, in motion - they are the same, as it should be.
Img and handler in constructor:
img = new Sprite(new Texture(finSize));
centerX = Gdx.graphics.getWidth()/2-img.getWidth()/2;
centerY = Gdx.graphics.getHeight()/2-img.getHeight()/2;
startPosition = new Vector2(centerX, centerY);
Gdx.input.setInputProcessor(new InputAdapter(){
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(img.getBoundingRectangle().contains(screenX, screenY))
System.out.println("Image Clicked");
return true;
}
});
Render:
public void render(SpriteBatch batch, float radius, float boost) {
speed+=boost;
nextX = radius * (float) Math.cos(speed); // Offset step X
nextY = radius * (float) Math.sin(speed); // Offset step Y
// Img is moving, but clicks is not handling
img.setBounds(startPosition.x+ nextX, startPosition.y + nextY, 100, 100);
// Handling clicks fine, but img is motionless
img.setBounds(startPosition.x, startPosition.y, 100, 100);
img.draw(batch);
// Checking coordinates - all's fine
System.out.println(img.getBoundingRectangle().getX());
System.out.println(startPosition.x + nextX);
System.out.println(img.getBoundingRectangle().getY());
System.out.println(startPosition.y + nextY);
}
So, I sequentially compared the XY coordinates of the image and the mouse click point and came to the conclusion that InputAdaper and Sprite consider Y differently - from above and from below. Therefore, X always coincided, and Y had a big difference in values.
As a result, I entered two corrected coordinates xPos \ yPos (Y subtracted from the total field height) for the center of the pic and in the touchDown() method, instead of comparing with BoundRectangle, simply compared the difference in the coordinates of the pic and the click modulo. If the result into the image size range - everything is ok.
Now clicks on the moving image works correctly.
public void render(SpriteBatch batch, float radius, float boost) {
speed+=boost; // rotational speed
nextX = radius * (float) Math.cos(speed); // Offset step X
nextY = radius * (float) Math.sin(speed); // Offset step Y
// set image size and position
img.setBounds(startPosition.x+nextX, startPosition.y+nextY, 100, 100);
img.draw(batch);
// Corrected coordinates of the image for InputAdapter coordinate system
xPos = img.getX()+img.getWidth()/2;
yPos = Gdx.graphics.getHeight()-img.getY()- img.getHeight()/2;
// Check the coincidence of the coordinates of the image area and the click point
Gdx.input.setInputProcessor(new InputAdapter(){
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if((Math.abs(xPos-screenX)<=img.getWidth()) && (Math.abs(yPos-screenY)<=img.getHeight()))
{System.out.println("Image Clicked");}
return true;
}
});
}

Blending motion for circles

How can I blend a moving circle's motion in an CPU efficient way which still allows for fairly accurate collision detection? I've tried stretching and rotating and ellipse, but it looks unnatural. I've tried drawing in between objects my sketch below. But the motion is still jagged between the frames, and it's expensive to draw a lot of in between circles with transparency. Is there a better way to do this? For example, bridging the shapes or smoothing motion with a bezier transformation? Maybe holding the last two locations in an array and using the current and last two to draw a bezier curve and drawing a curved shape between the last location and current location with the data from all three points? How do you deal with fast motion where you need to avoid the "..." effect, but also need to use the current location for collision detection and so on?
int xprev;
int yprev;
int xcur;
int ycur;
float size = 10;
float scale;
int rotation = 0;
void setup() {
size(600, 600);
}
void draw () {
background(0);
xcur= int(cos(radians(rotation))*200) + width/2;
ycur = int(sin(radians(rotation))*200) + height/2;
rotation = rotation + 5;
//scale = dist(xcur, ycur, xprev, yprev)/2;
//println(scale);
drawEllipse();
xprev = xcur;
yprev = ycur;
}
void drawEllipse() {
for (int i = 1; i < 10; i++) {
noStroke();
fill(255, i*20);
ellipse(xprev+ (xcur - xprev) * i/10, yprev + (ycur - yprev) * i/10, size, size);
}
fill(255);
ellipse(xcur, ycur, size, size);
}

Java detect collision for fast moving objects

I have problem, that balls that move too fast can fly through wall (walls are 4 pixels wide, and speed of ball occasionally is more than 400 pixels per second (which is more than 4 pixels per update assuming fps is 60)). I researched it on StackOverflow, but the solution for others is not suitable for me, as they are using rectangles, and i am using pixel collision. Here is method which returns if ball intersects with wall (method is in Ball class):
public boolean intersects(Wall w) {
BufferedImage im1 = new BufferedImage (size, size, BufferedImage.TYPE_INT_ARGB); // size is diameter of the ball
BufferedImage im2 = new BufferedImage (size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g1 = im1.createGraphics();
Graphics2D g2 = im2.createGraphics();
g1.translate(-x + size/2, -y + size/2);
g2.translate(-x + size/2, -y + size/2);
render(g1);
w.render(g2);
g1.dispose();
g2.dispose();
for (int x = 0; x < im1.getWidth(); x++){
for (int y = 0; y < im1.getHeight(); y++){
Color c1 = new Color(im1.getRGB(x, y), true);
Color c2 = new Color(im2.getRGB(x, y), true);
if (c1.getAlpha() != 0 && c2.getAlpha() != 0){
return true;
}
}
}
return false;
}
Here is how ball is drawn:
public void render(Graphics2D g) {
color = new Color (Color.HSBtoRGB(hue, 0.5f, 0.5f));
g.setColor (color);
g.fillOval((int)(x-size/2), (int) (y-size/2), size, size);
}
The wall is simply defined as 2 points, and here is how wall is drawn:
public void render(Graphics2D g2) {
g2.setColor(new Color(r, g, b));
g2.setStroke(new BasicStroke(width)); //width = 4
g2.draw(new Line2D.Float(p1.x, p1.y, p2.x, p2.y));
}
I have a couple of quick ideas that you might want to attempt.
Why not check the endpoints against the dimensions of the wall (some simple algebra and I think what you might already be trying to do). If you need help with the algebra involved I'll include a link below. Basically just record the starting point of the ball (prior to moving), and on update check the old location versus the estimated location, and run a function to see if a collision occurs. This will become tricky however if you want realistic physics.
https://gamedev.stackexchange.com/questions/26004/how-to-detect-2d-line-on-line-collision
In the above link, just assume your walls are one line, and the previous coordinates and the expected next coordinates of the ball form the other line. This method works very well if you only have the ball moving in straight lines.
Your only alternative might be to have two simultaneous models running (basically a visual space which you have in showing the ball and walls, and a virtual setup checking the physics behind what you are showing.

Dragging rotated text inside android canvas does not work as expected

There is something I am missing inhere so I hope you can share some light on me.
I am drawing some text inside canvas. For this I have a class Word
public class Word {
private int x;
private int y;
private String text;
}
The app allows the user to rotate the text, and I handle the rotation withing onDraw
protected void onDraw(Canvas canvas) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.rotate(angle, centerX, centerY)
...
canvas.drawText(word.getText(), word.getX(), word.getY())
....
canvas.restore();
}
The problem I get is when the user drags the canvas and there is a rotation set. When angle=0 the movement is going as expected.
#Override
public boolean onTouchEvent(MotionEvent event) {
case MotionEvent.ACTION_DOWN:
initialX = (int) event.getX();
initialY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int currentX = (int) event.getX();
int currentY = (int) event.getY();
int xMovement = currentX - initialX;
int yMovement = currentY - initialY;
dragWords(xMovement, yMovement);
.....
and on dragWords for each word I do:
private void dragText(int xMovement, int yMovement){
for (Word word : words) {
word.setX(word.getX() + xMovement);
word.setY(word.getY() + yMovement);
}
invalidate();
}
When rotation angle is 0, moving up/down/left/right makes the words move by the same distance. As angle gets bigger, the words start to move in different dirrections, for instance at 60, it is starting to go diagonally up, when 180 it only moves up/down and not left/right.
I think I need to calculate some sort of a difference based on angle and add it to xMovement/yMovement... but how should I do this ?
LE: Here is an image on how it behaves:
The blue lines is how the text is moving on drag while the orange is the finger dragging on the screen. When angle is 0 it works quite well, when angle increases, it starts to move diagonally on left/right, while when angle is even bigger, it only moves up and down and does not respond to left/right
If I understand correctly, the issue is that Canvas.rotate() does not only rotate the text direction, but rather the whole canvas. Therefore, the x-y coordinates of the words are also rotated from the specified pivot point.
In order to match the dragging movement, you can use a Matrix for this, more specifically the inverse matrix of the one you're using to rotate the canvas. It will be used to convert the x-y coordinates of the words to their original, pre-rotate locations.
For example, calculate this once, and update it whenever angle, centerX, or centerY changes.
// rotMatrix is the same operation applied on the canvas.
Matrix rotMatrix = new Matrix();
rotMatrix.postRotate(mAngle, centerX, centerY);
// Invert it to convert x, y to their transformed positions.
Matrix matrix = new Matrix();
rotMatrix.invert(matrix);
Then, when drawing each word:
int wordX = ...
int wordY = ...
String text = ...
float[] coords = new float[] { wordX, wordY };
matrix.mapPoints(coords);
canvas.drawText(text, coords[0], coords[1], paint);
In the ellipses part in the following code:
dragWords(xMovement, yMovement);
..... <<<--------------------- I hope you are updating initialX and initialY
initialX = currentX;
initialY = currentY;
Otherwise, your x and y values will not correspond correctly with the amount of distance moved during the touch gesture.
As user matiash indicated, you should use Matrix#mapPoints(float[]) to transform your x and y values. Declare and initialize a Matrix:
Matrix correctionMatrix;
// Your view's constructor
public MyView() {
....
correctionMatrix = new Matrix();
}
Here's how your onDraw(Canvas) should look like:
#Override
protected void onDraw(Canvas canvas) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.rotate(angle, centerX, centerY);
...
// Neutralize the rotation
correctionMatrix.setRotate(-angle, centerX, centerY);
// Initialize a float array that holds the original coordinates
float[] src = {word.getX(), word.getY()};
// Load transformed values into `src` array
correctionMatrix.mapPoints(src);
// `src[0]` and `src[1]` hold the transformed `X` and `Y` coordinates
canvas.drawText(word.text, src[0], src[1], somePaint);
....
canvas.restore();
}
This should give you the desired results - movement in the X and Y axis irrespective of canvas rotation.
You can obviously move the call to setRotate(float, float, float) to a better place. You only need to call it once after changing the angle value.

Java applet crashes when I try to crop a picture

I've been trying to chop up a larger picture and use it as tiles for a game. I had the program working using fillRect() to simulate the image. However, when I replace the fillRect code, it crashes. Here is what I've been using:
buffer.drawImage(section[i][j].getSectionImage(i, j),
sectionSize * i + OFFSETx,
sectionSize * j + OFFSETy,
this);
public class Section{
private static ImageIcon ii;
private static Image mainImage;
private Image sectionImage;
public Section(){
if (ii == null){
ii = new ImageIcon(this.getClass().getResource("images/Mossy_rocks.png"));
mainImage = ii.getImage();
}
}
public Image getSectionImage(int x, int y){
sectionImage = createImage(new FilteredImageSource(mainImage.getSource(),
new CropImageFilter(1,1,20,20))); //test values
return sectionImage;
}
}
I tried "extends JApplet/JFrame/JComponent" for the Section Class, but it didn't seem to help.
Edit: I would also like to mention that if I would just return mainImage from getSectionImage(), I get the image. I think the biggest problem is the rest of that function... but I'm not sure, so I included everything I needed to add when replacing fillRect().
I found a much better way to crop this image. Here is how I did it:
screenImage.drawImage(Image sprite,
int (x position on screen),
int (y position on screen),
int (x position on screen + width),
int (y position on screen + height),
int (x position from sprite),
int (y position from sprite),
int (x position from sprite + width),
int (y position from sprite + height),
null);

Categories

Resources