I have a question regarding rendering with box2d and libgdx.
As you can see in the screenshot below I have a problem when changing the window resolution.
Box2d gets scaled over the entire screen although the viewport is only using a small portion of it. Also the lights get scaled and do not match the real position anymore (but I think this is related to the same issue).
My idea is that I somehow need to adjust the matrix (b2dCombinedMatrix) for box2d before rendering but I have no idea how.
Personally I think that I need to tell it that it should use the same "render boundaries" as the viewport but I cannot figure out how to do that.
Here is the render method (the issue is after the draw lights comments part):
public void render(final float alpha) {
viewport.apply();
spriteBatch.begin();
AnimatedTiledMapTile.updateAnimationBaseTime();
if (mapRenderer.getMap() != null) {
mapRenderer.setView(gameCamera);
for (TiledMapTileLayer layer : layersToRender) {
mapRenderer.renderTileLayer(layer);
}
}
// render game objects first because they are in the same texture atlas as the map so we avoid a texture binding --> better performance
for (final Entity entity : gameObjectsForRender) {
renderEntity(entity, alpha);
}
for (final Entity entity : charactersForRender) {
renderEntity(entity, alpha);
}
spriteBatch.end();
// draw lights
b2dCombinedMatrix.set(spriteBatch.getProjectionMatrix());
b2dCombinedMatrix.translate(0, RENDER_OFFSET_Y, 0);
rayHandler.setCombinedMatrix(b2dCombinedMatrix, gameCamera.position.x, gameCamera.position.y, gameCamera.viewportWidth, gameCamera.viewportHeight);
rayHandler.updateAndRender();
if (DEBUG) {
b2dRenderer.render(world, b2dCombinedMatrix);
Gdx.app.debug(TAG, "Last number of render calls: " + spriteBatch.renderCalls);
}
}
And this is the resize method which moves the viewport up by 4 world units:
public void resize(final int width, final int height) {
viewport.update(width, height, false);
// offset viewport by y-axis (get distance from viewport to viewport with offset)
renderOffsetVector.set(gameCamera.position.x - gameCamera.viewportWidth * 0.5f, RENDER_OFFSET_Y + gameCamera.position.y - gameCamera.viewportHeight * 0.5f, 0);
gameCamera.project(renderOffsetVector, viewport.getScreenX(), viewport.getScreenY(), viewport.getScreenWidth(), viewport.getScreenHeight());
viewport.setScreenY((int) renderOffsetVector.y);
}
After hours of fiddling around with the matrix I finally got it to work but there is actually a very easy solution to my problem :D
Basically the render method of the rayhandler was messing up my matrix calculations all the time and the reason is that I did not tell it to use a custom viewport.
So adjusting the resize method to this
public void resize(final int width, final int height) {
viewport.update(width, height, false);
// offset viewport by y-axis (get distance from viewport to viewport with offset)
renderOffsetVector.set(gameCamera.position.x - gameCamera.viewportWidth * 0.5f, RENDER_OFFSET_Y + gameCamera.position.y - gameCamera.viewportHeight * 0.5f, 0);
gameCamera.project(renderOffsetVector, viewport.getScreenX(), viewport.getScreenY(), viewport.getScreenWidth(), viewport.getScreenHeight());
viewport.setScreenY((int) renderOffsetVector.y);
rayHandler.useCustomViewport(viewport.getScreenX(), viewport.getScreenY(), viewport.getScreenWidth(), viewport.getScreenHeight());
}
and simplifying the render method to
// draw lights
rayHandler.setCombinedMatrix(gameCamera);
rayHandler.updateAndRender();
if (DEBUG) {
b2dRenderer.render(world, b2dCombinedMatrix);
Gdx.app.debug(TAG, "Last number of render calls: " + spriteBatch.renderCalls);
}
solved my problem.
Maybe I am stupid but I did not find useCustomViewport method in any of the documentations.
Anyway , solved!
Related
I want to pick up a color from drawn canvas.
I found get() function, but it can get color only from image.
Is there some way to get color from current canvas?
You can get() colour from your current canvas: just address the PGraphics instance you need (even the global one) and be sure to call loadPixels() first.
Here's tweaked version of Processing > Examples > Basics > Image > LoadDisplayImage:
/**
* Load and Display
*
* Images can be loaded and displayed to the screen at their actual size
* or any other size.
*/
PImage img; // Declare variable "a" of type PImage
void setup() {
size(640, 360);
// The image file must be in the data folder of the current sketch
// to load successfully
img = loadImage("https://processing.org/examples/moonwalk.jpg"); // Load the image into the program
}
void draw() {
// Displays the image at its actual size at point (0,0)
image(img, 0, 0);
// Displays the image at point (0, height/2) at half of its size
image(img, 0, height/2, img.width/2, img.height/2);
//load pixels so they can be read via get()
loadPixels();
// colour pick
int pickedColor = get(mouseX,mouseY);
// display for demo purposes
fill(pickedColor);
ellipse(mouseX,mouseY,30,30);
fill(brightness(pickedColor) > 127 ? color(0) : color(255));
text(hex(pickedColor),mouseX+21,mouseY+6);
}
It boils down to calling loadPixels(); before get().
Above we're reading pixels from the sketch's global PGraphics buffer.
You can apply the same logic but reference a different PGraphics buffer depending on your setup.
I have used Animation() method to make my view with the animation of scaling and Rotation. With the Rotation based on the Y axis, the default height and width of my view has been changed. It looks like the parallelogram.
rotation of rectangle along y-axis transformed to a parallelogram.
myview.Animate().RotationY(rotationangle)
.X(xposition)
.SetDuration(mduration)
.WithLayer()
.SetInterpolator(interpolate).Start();
My requirement:
I just want the rotation of my view no need to change its projection. How to restrict the rotation of rectangle along y-axis transformed to a parallelogram.
For more reference, please check the attached sample
now view be like,
Image
Please share your idea.
Thanks in Advance.
Note: while using PivotX and PivotY, there is no parallelogram shape. But I don't know the exact usage of that.
Regards,
Hemalatha Marikumar
is that not what are you looking for ?
it may work if you put this code in your current activity
Android: Temporarily disable orientation changes in an Activity
Do you want to create a 2D rotation?
You could try to use ScaleAnimation to rotate the view. If you want to rotate 360 degrees, you could use AnimationListener.
For example:
Button myview = (Button)FindViewById(Resource.Id.button2);
ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0, 1, 1,
Android.Views.Animations.Dimension.RelativeToParent, 0.5f, Android.Views.Animations.Dimension.RelativeToParent, 0.5f);
ScaleAnimation scaleAnimation2 = new ScaleAnimation(0, 1, 1, 1,
Android.Views.Animations.Dimension.RelativeToParent, 0.5f, Android.Views.Animations.Dimension.RelativeToParent, 0.5f);
scaleAnimation.Duration = 4000;
scaleAnimation.SetAnimationListener(new AnimationListener(myview, scaleAnimation2));
scaleAnimation2.Duration = 4000;
myview.StartAnimation(scaleAnimation);
The Listener:
public class AnimationListener :Java.Lang.Object, IAnimationListener
{
View view;
Animation animation2;
public AnimationListener(View view, Animation animation)
{
this.view = view;
this.animation2 = animation;
}
public void OnAnimationEnd(Animation animation)
{
view.StartAnimation(animation2);
}
public void OnAnimationRepeat(Animation animation)
{
}
public void OnAnimationStart(Animation animation)
{
}
}
I am trying to rotate a vector I have created in illustrator using processing. I would like it to rotate this vector from it's center so it appears to be spinning as oppose to moving around an invisible point. Below is my attempt:
PShape WOE;
void setup(){
WOE = loadShape("WOE.svg");
size (500, 500);
smooth();
}
void draw(){
background(20);
shape(WOE, width/2, height/2, WOE.width, WOE.height); //draw shape in "center" of canvas (250, 250)
translate(-WOE.width/2, -WOE.height/2); //move shape so that center of shape is aligned with 250, 250
WOE.rotate(0.01);
}
From a strictly logical point of view this should work, however this results in the vector rotating around the center of the canvas, but approximately 100px away. I have tried using shapeMode(CENTER); but this unfortunately causes no improvement. Hope someone can help, thanks!
For Reference
Here is WOE.svg: https://www.dropbox.com/s/jp02yyfcrrnep93/WOE.svg?dl=0
I think part of your problem is that you're mixing rotating the shape and translating the entire sketch. I would try to stick with one or the other: either translate and rotate the entire sketch, or only translate and rotate the shape.
That being said, I'm not surprised this gave you trouble.
I would expect this to work:
PShape WOE;
void setup() {
size (500, 500);
WOE = loadShape("WOE.svg");
WOE.translate(-WOE.width/2, -WOE.height/2);
}
void draw() {
background(20);
WOE.rotate(.01);
shape(WOE, width/2, height/2);
}
However, this exhibits the same off-center behavior you're noticing. But if I switch to the P2D renderer, it works fine!
size (500, 500, P2D);
Now the shape is centered in the window and rotates around the shape's center. The difference between renderers seems buggy, but I can't find an open bug on GitHub. Edit: I found this SO question, which lead to this GitHub issue.
In any case, it might be easier to rotate the entire sketch instead of the shape:
PShape WOE;
float rotation = 0;
void setup() {
size (500, 500);
WOE = loadShape("WOE.svg");
shapeMode(CENTER);
}
void draw() {
background(20);
translate(width/2, height/2);
rotate(rotation);
shape(WOE);
rotation += .01;
}
This code works by translating the entire sketch to the center of the window, then rotating the entire sketch, then drawing the shape. Think of this like moving the camera instead of moving the shape. If you have other stuff to draw, then you can use the pushMatrix() and popMatrix() functions to isolate the transformation. This works the same in the default renderer and the P2D renderer.
I would like to rotate a sprite on the scene by pressing the left or right arrows keys (think of the spaceship in Asteroids).
I have placed the sprite in question on the scene and created a script, but am not really certain of where to go from there.
My current script looks like this:
using UnityEngine;
using System.Collections;
public class RotateLeftRight : MonoBehaviour {
public float speed = 1.0f;
public string axisName = "Horizontal";
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
// left
transform.Rotate(-1.0f, 0.0f, 0.0f); // does nothing, just a bad guess
}
if(Input.GetKeyDown(KeyCode.RightArrow)) {
// right
transform.Rotate(1.0f, 0.0f, 0.0f); // does nothing, just a bad guess
}
}
}
I just coded the above without any knowledge of what would happen (and, hardly surprising, nothing appears to happen at all).
Any advice on how to rotate the sprite and control the speed of the rotation would be greatly appreciated.
I'm not able to try it with Unity right now, but my guess is that it is either rotating just 1º, so you are not able to notice it, or rotating 360º, and so it really stays the same.
Try to break down your problem:
Instead of transform.Rotate try transform.Translate(20f, 20f, 20f) just to make sure it is recognizing the input;
Use a different value instead of 1.0f, such as 0.1f and 30.0f (I think 30.0f would be 30º, but I'm not sure);
Try changing the rotation on the other axes y and z instead of x;
Use the alternative definition Rotate(Vector3 axis, float angle).
Hope it helps!
#Sailing Judo, here's the best answer if you want to rotate it like a wheel. Try observe again to your code and instead of putting/changing the X-axis as parameter, put your value at the Z-axis instead. Changing x or y-axis in a circular rotation ended up like flipping coins. Observe and try again.
if(Input.GetKey(KeyCode.LeftArrow)) {
// Clockwise
transform.Rotate(0, 0, -3.0f); // --> Instead of "transform.Rotate(-1.0f, 0.0f, 0.0f);"
}
if(Input.GetKey(KeyCode.RightArrow)) {
// Counter-clockwise
transform.Rotate(0, 0, 3.0f); // --> Instead of transform.Rotate(1.0f, 0.0f, 0.0f);
}
I'm trying to include support for zooming and rotating my camera class, around the centre of the viewport.
In my application, I've already positioned sprites manually before entering the SpriteBatch.Begin code, according to where the camera is positioned (to make culling easier to implement). Although each sprite is positioned manually, I would rather not rotate and scale each sprite individually.
I therefore am trying to use the matrixTransform argument on the SpriteBatch.Begin method.
Below is a hard-coded application I've made to illustrate the problem (using a Car.png content image). The rotation isn't as fast as I'd expect (10 degrees rotation every frame?), and it rotates/zooms about the top left. I would like it to rotate around the centre of the screen, which would always keep the middle car in the centre, and also scale from that point.
I have tried several combinations of creating matrix translations, reordering/adding/multiplying/translating by the halfway distance of viewport, but I don't really understand how matrices work. I've also tried the solutions on several websites which I haven't managed to make work for me.
Can someone tell me the matrix translations I have to create, or point me in the direction of a website you think will work for my setup?
Windows XNA application to demonstrate the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace RenderTest
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D _carTexture;
float _zoom = 1.0f;
float _rotationInDegrees = 0.0f;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
_carTexture = Content.Load<Texture2D>("Car");
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up)) // Zoom in key
_zoom *= 1.1f;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Down)) // Zoom out key
_zoom /= 1.1f;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Left)) // Rotate anticlockwise key
_rotationInDegrees -= 10;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Right)) // Rotate clockwise key
_rotationInDegrees += 10;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullNone, null, GetMatrix(GraphicsDevice));
spriteBatch.Draw(_carTexture, new Rectangle(0, 0, 50, 50), Color.White);//Square car placed top left
spriteBatch.Draw(_carTexture, new Rectangle(GraphicsDevice.Viewport.Width / 2 - 25, GraphicsDevice.Viewport.Height / 2 - 50, 50, 100), Color.Green);//Car placed centre
spriteBatch.Draw(_carTexture, new Rectangle(GraphicsDevice.Viewport.Width / 2 + 100, GraphicsDevice.Viewport.Height / 2 + 100, 50, 50), Color.Black);//Off centre but always within screen
spriteBatch.End();
base.Draw(gameTime);
}
Matrix GetMatrix(GraphicsDevice graphicsDevice)
{
Matrix translationMatrix = Matrix.CreateTranslation(0, 0, 0);
Matrix rotationMatrix = Matrix.CreateRotationZ(MathHelper.ToRadians(MathHelper.ToRadians(_rotationInDegrees)));
Matrix zoomMatrix = Matrix.CreateScale(_zoom);
Matrix compositeMatrix = translationMatrix * rotationMatrix * zoomMatrix;
return compositeMatrix;
}
}
}
Thanks,
Lee
Solution
Matrix GetMatrix(GraphicsDevice graphicsDevice)
{
Matrix translateToOrigin = Matrix.CreateTranslation(-graphicsDevice.Viewport.Width / 2, -graphicsDevice.Viewport.Height / 2, 0);
Matrix rotationMatrix = Matrix.CreateRotationZ(MathHelper.ToRadians(_rotationInDegrees));
Matrix zoomMatrix = Matrix.CreateScale(_zoom);
Matrix translateBackToPosition = Matrix.CreateTranslation(graphicsDevice.Viewport.Width / 2, graphicsDevice.Viewport.Height / 2, 0);
Matrix compositeMatrix = translateToOrigin * rotationMatrix * zoomMatrix * translateBackToPosition;
return compositeMatrix;
}
You should use the same Rectangle each time, and do the positioning in the matrix.
The reason for this is that the matrix is applied to your sprites after they are positioned using rectangle. All subseqent matrix operations will treat (0,0) as the origin, instead of the center of the texture as you expected.