How to repair the spacing between blocks when I rotate them? - c++

Hello I'm currently trying to rotate blocks that are within a square. But when I start to rotate them it starts to create weird spaces between blocks that I don't want. Could you help me to fix the problem of spaces beetween blocks? Here are some code and screenshots how does it look.
https://imgur.com/a/BLuO7FF
I have already checked if all angles and radiuses are calculated correctly and I don't see any problem there.
World.h
#pragma once
#include <SFML/Graphics.hpp>
class World
{
public:
World(sf::Vector2f Wpos);
float AngleToRadian(int angle);
void RotateWorld();
void draw(sf::RenderWindow &window);
sf::Texture tx;
sf::Sprite** Block;
sf::Vector2f Pos;
sf::Vector2i Size;
float** radius;
float** angle;
};
World.cpp
#include "World.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cmath>
#define PI 3.14159
World::World(sf::Vector2f Wpos)
{
Pos = Wpos;
Size = sf::Vector2i(10, 10);
Block = new sf::Sprite*[Size.y];
radius = new float*[Size.y];
angle = new float*[Size.y];
for (int i = 0; i < Size.y; i++)
{
Block[i] = new sf::Sprite[Size.x];
radius[i] = new float[Size.x];
angle[i] = new float[Size.x];
}
tx.loadFromFile("Img/Block.png");
sf::Vector2i off(Size.x * tx.getSize().x / 2, Size.y * tx.getSize().y / 2); //tx size is 32px x 32px
for (int y = 0; y < Size.y; y++)
{
for (int x = 0; x < Size.x; x++)
{
Block[y][x].setTexture(tx);
Block[y][x].setOrigin(tx.getSize().x / 2, tx.getSize().y / 2);
Block[y][x].setPosition(x*tx.getSize().x + Wpos.x - off.x + Block[y][x].getOrigin().x, y*tx.getSize().y + Wpos.y - off.y + Block[y][x].getOrigin().y);
radius[y][x] = sqrt(pow(Pos.x - Block[y][x].getPosition().x, 2) + pow(Pos.y - Block[y][x].getPosition().y, 2));
angle[y][x] = (atan2(Block[y][x].getPosition().y - Pos.y, Block[y][x].getPosition().x - Pos.x) * 180.0) / PI;
if ((atan2(Block[y][x].getPosition().y - Pos.y, Block[y][x].getPosition().x - Pos.x) * 180.0) / PI < 0)
{
angle[y][x] += 360;
}
//angle[y][x] = round(angle[y][x]);
/*radius[y][x] = round(radius[y][x]);*/
}
}
}
void World::RotateWorld()
{
float dx = 0, dy = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
for (int y = 0; y < Size.y; y++)
{
for (int x = 0; x < Size.x; x++)
{
Block[y][x].rotate(1);
if (angle[y][x] >= 360)
{
angle[y][x] = 0;
}
angle[y][x]++;
dx = cos(AngleToRadian(angle[y][x])) * radius[y][x];
dy = sin(AngleToRadian(angle[y][x])) * radius[y][x];
Block[y][x].setPosition(Pos.x + dx, Pos.y + dy);
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
{
for (int y = 0; y < Size.y; y++)
{
for (int x = 0; x < Size.x; x++)
{
Block[y][x].rotate(-1);
if (angle[y][x] >= 360)
{
angle[y][x] = 0;
}
angle[y][x]--;
dx = cos(AngleToRadian(angle[y][x])) * radius[y][x];
dy = sin(AngleToRadian(angle[y][x])) * radius[y][x];
Block[y][x].setPosition(Pos.x + dx, Pos.y + dy);
}
}
}
}
I expected it to rotate withouth any spaces between. I would be really thankfull if someone would help me.

I would try with setting the origin of the sf::Sprite using it's getGlobalBounds() method instead of the sf::Texture size getter.
The difference seems minor and something like that might be the case.
Block[y][x].setTexture(tx);
Block[y][x].setOrigin(Block[y][x].getGlobalBouds().width / 2, Block[y][x].getGlobalBouds().height / 2);
Block[y][x].setPosition(x*Block[y][x].getGlobalBouds().width + Wpos.x - off.x + Block[y][x].getOrigin().x, y*Block[y][x].getGlobalBouds().height + Wpos.y - off.y + Block[y][x].getOrigin().y);

Related

How can I find out the size of the title bar using SDL?

Faced the following problem: I have a grid and a beam, in the form of a circle. At this stage, you just need to draw them.
Grid::render():
for (int i = 0; i < cellsInColumn; i++) {
for (int j = 0; j < cellsInRow; j++) {
SDL_Rect outlineRect = { this->x + this->bord_x + (cellWidth*j), this->y+this->bord_y, this->cellWidth, this->cellHeight };
SDL_RenderDrawRect( this->rend, &outlineRect );
}
y+=cellHeight;
}
Beam::render():
for (int w = 0; w < radius * 2; w++) {
for (int h = 0; h < radius * 2; h++) {
double dx = radius - w;
double dy = radius - h;
if ((dx*dx + dy*dy) <= (radius * radius)) {
SDL_RenderDrawPoint(this->rend, x + dx, y + dy);
}
}
}
But my screen seems to have "eaten" the top line of the grid. It turned out that the top of the grid, along with the "beam", was drawn under the title bar.
bord_y == 0
bord_y == 70
Question for the connoisseurs: how do I now draw the grid and the circle? Does the SDL know how many pixels are in the title bar, or should this indent be "by eye"? If it knows, where is this information stored?
UPD:
Grid and beam values are set in the following function:
void setStartValues(int screenWidth, int screenHeight){
Grid::setBord(screenWidth, screenHeight);
Grid::setCellSize(screenHeight);
Beam::setValues(Grid::getCellHeight(), Grid::getBord());
}
And here are all the getters and setters that are used above:
void setBord(int scrW, int scrH) {
this->bord_x = this->cellsInRow <= this->cellsInColumn? (scrW-scrH)/2 : (scrW-scrH)/6;
this->bord_y = 0;
}
void setCellSize(int scrH) {
this->cellWidth = this->cellHeight = scrH/cellsInColumn;
}
double getCellHeight() {
return this->cellHeight;
}
double getBord() {
return this->bord_x;
}
void setValues(double cellH, double bord) { //Beam
this->x = cellH/2 + bord;
this->y = cellH/2;
this->radius = cellH/4;
}

How to render an AABB while rotating

Hello I'm new to C++ SFML. I'm supposed to draw some rectangles and render their AABB while rotating and I want to detect if the dimensions set for them intersect another rotating AABB rectangle. Here is what I use to detect them.
Is it enough to check it that way if theyre rotating? would i need to use stuff like the separating axis theorem? or is there a way to not need to use that if its just an AABB than an OBB
#define RECT 5
sf::RectangleShape Rect[RECT];
Rect[0].setSize(sf::Vector2f(50.0f, 50.0f));
Rect[1].setSize(sf::Vector2f(50.0f, 100.0f));
Rect[2].setSize(sf::Vector2f(60.0f, 80.0f));
Rect[3].setSize(sf::Vector2f(100.0f, 60.0f));
Rect[4].setSize(sf::Vector2f(30.0f, 250.0f));
sf::Vector2f MinPoint[RECT];
sf::Vector2f MaxPoint[RECT];
for (int x = 0; x < RECT; x++)
{
//Starting Position
Rect[x].setOrigin(Rect[x].getSize().x / 2, Rect[x].getSize().y / 2);
xpos += 150;
Rect[x].setPosition(xpos, ypos);
colcount++;
if (colcount == 3)
{
xpos = 0;
ypos += 200;
colcount = 0;
}
Rect[x].setFillColor(sf::Color::Red);
}
while (window.isOpen())
{
window.clear(sf::Color::Black);
//Drawing Shapes
for (int x = 0; x < RECT; x++)
{
window.draw(Rect[x]);
}
Rect[0].rotate(90*3.14/180);
Rect[1].rotate(12 * 3.14 / 180);
Rect[2].rotate(10 * 3.14 / 180);
Rect[3].rotate(180 * 3.14 / 180);
Rect[4].rotate(360 * 3.14 / 180);
for (int i = 0; i < RECT; i++)
{
MinPoint[i].x = Rect[i].getPosition().x - (Rect[i].getSize().x / 2);
MaxPoint[i].x = Rect[i].getPosition().x + (Rect[i].getSize().x / 2);
MinPoint[i].y = Rect[i].getPosition().y - (Rect[i].getSize().y / 2);
MaxPoint[i].y = Rect[i].getPosition().y + (Rect[i].getSize().y / 2);
}
//Collision Detection
for (int i = 0; i < RECT; i++)
{
for (int j = i + 1; j < RECT; j++)
{
if (i != j)
{
if (MaxPoint[i].x >= MinPoint[j].x && MaxPoint[j].x >= MinPoint[i].x && MaxPoint[i].y >= MinPoint[j].y && MaxPoint[j].y >= MinPoint[i].y)
{
Rect[i].setFillColor(sf::Color::Green);
Rect[j].setFillColor(sf::Color::Green);
}
}
}
}
Apparently all I needed to do was make another set of transparent rectangles with outlines that were set at the same position as my rotating rectangle boxes then set their sizes to getGlobalBounds of my rotating rectangles. the collision check would then instead be put under these transparent bounding boxes instead of the rotating rectangle itself.
#define RECT 5
sf::RectangleShape Rect[RECT];
sf::RectangleShape AABB[RECT];
Rect[0].setSize(sf::Vector2f(50.0f, 50.0f));
Rect[1].setSize(sf::Vector2f(50.0f, 100.0f));
Rect[2].setSize(sf::Vector2f(60.0f, 80.0f));
Rect[3].setSize(sf::Vector2f(100.0f, 60.0f));
Rect[4].setSize(sf::Vector2f(30.0f, 250.0f));
sf::Vector2f MinPoint[RECT];
sf::Vector2f MaxPoint[RECT];
for (int x = 0; x < RECT; x++)
{
//Starting Position
Rect[x].setOrigin(Rect[x].getSize().x / 2, Rect[x].getSize().y / 2);
AABB[x].setOrigin(AABB[x].getSize().x / 2, AABB[x].getSize().y / 2);
xpos += 150;
Rect[x].setPosition(xpos, ypos);
AABB[x].setSize(sf::Vector2f(Rect[x].getGlobalBounds().width, Rect[x].getGlobalBounds().height));
AABB[x].setPosition(Rect[x].getPosition().x, Rect[x].getPosition().y);
colcount++;
if (colcount == 3)
{
xpos = 0;
ypos += 200;
colcount = 0;
}
Rect[x].setFillColor(sf::Color::Red);
AABB[x].setFillColor(sf::Color::Transparent);
AABB[x].setOutlineThickness(1);
AABB[x].setOutlineColor(sf::Color::White);
}
while (window.isOpen())
{
window.clear(sf::Color::Black);
//Drawing Shapes
for (int x = 0; x < RECT; x++)
{
window.draw(Rect[x]);
window.draw(AABB[x]);
}
//Rotation
Rect[0].rotate(1);
Rect[1].rotate(45);
Rect[2].rotate(11.25);
Rect[3].rotate(5.625);
Rect[4].rotate(22.5);
for (int i = 0; i < RECT; i++)
{
MinPoint[i].x = AABB[i].getPosition().x - (AABB[i].getSize().x / 2);
MaxPoint[i].x = AABB[i].getPosition().x + (AABB[i].getSize().x / 2);
MinPoint[i].y = AABB[i].getPosition().y - (AABB[i].getSize().y / 2);
MaxPoint[i].y = AABB[i].getPosition().y + (AABB[i].getSize().y / 2);
AABB[i].setOrigin(AABB[i].getSize().x / 2, AABB[i].getSize().y / 2);
AABB[i].setSize(sf::Vector2f(Rect[i].getGlobalBounds().width, Rect[i].getGlobalBounds().height));
AABB[i].setPosition(Rect[i].getPosition().x, Rect[i].getPosition().y);
}
//Collision Detection
for (int i = 0; i < RECT; i++)
{
for (int j = i + 1; j < RECT; j++)
{
if (i != j)
{
if (MaxPoint[i].x >= MinPoint[j].x && MaxPoint[j].x >= MinPoint[i].x && MaxPoint[i].y >= MinPoint[j].y && MaxPoint[j].y >= MinPoint[i].y)
{
Rect[i].setFillColor(sf::Color::Green);
Rect[j].setFillColor(sf::Color::Green);
AABB[i].setOutlineColor(sf::Color::Blue);
AABB[j].setOutlineColor(sf::Color::Blue);
}
}
}
}

C++ Rotation matrix issue when used on a square

I'm attempting to apply an a rotation matrix in C++ that rotates all points of square a specified degree around a specified origin. The catch is that it is based in the win32 console, so each point has to correspond with a pair of ints, rather than floating point values. As you can see below, the rotating square's overall shape is consistent with the desired result, but there are a number of 'holes' in it.
Here's my source code:
#include <iostream>
#include <cmath>
using namespace std;
enum {W = 50, H = 50, S = 25}; //Width, Height, Square size
struct Vector2i
{
int x;
int y;
Vector2i() {}
Vector2i(int _x, int _y) : x(_x), y(_y) {}
};
struct Square
{
bool Data[W][H];
Vector2i Origin = Vector2i(W / 2, H / 2);
void clear() {
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x)
Data[x][y] = false;
}
}
void setSquare() {
for (int y = H / 2 - S / 2; y < H / 2 + S / 2; ++y) {
for (int x = W / 2 - S / 2; x < W / 2 + S / 2; ++x)
Data[x][y] = true;
}
}
void draw() {
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
if (y == Origin.y && x == Origin.x) std::cout << '+'; //Marks the origin
else if (Data[x][y]) std::cout << 'X';
else std::cout << '.';
}
std::cout << '\n';
}
}
};
Vector2i newPos(Vector2i old, double theta) {
theta *= 3.14159265d / 180.d; //Converting from degrees to radians
int X = ceil(cos(theta) * old.x - sin(theta) * old.y);
int Y = ceil(sin(theta) * old.x + cos(theta) * old.y);
return Vector2i(X, Y);
}
int main()
{
cout << "Enter an angle (in degrees): ";
double angle = 0;
cin >> angle;
Square One;
One.clear();
One.setSquare();
One.draw();
Square Two;
Two.clear();
///Draw the rotated square as the second square
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
if (One.Data[x][y]) {
Vector2i finalVec = newPos(Vector2i(x - One.Origin.x,
y - One.Origin.y), angle);
Two.Data[finalVec.x + One.Origin.x][finalVec.y + One.Origin.y] = true;
}
}
}
///Copy the second square back into the first
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x)
One.Data[x][y] = Two.Data[x][y];
}
One.draw();
return 0;
}
Is this due to the accuracy of the newPos() function, or is it the rounding into int values that is causing this?
Additionally, is there a way to fix this or predict where the holes will be?
EDIT: SOLVED!
Going off of infgeoax's suggestion to work backwards, I created a function to calculate the original positions. I'll leave the augmented code here, in case anyone has a similar problem in the future (Thanks for all your help, everyone! [especially infgeoax, for the brainwave]):
#include <iostream>
#include <cmath>
using namespace std;
enum {W = 50, H = 50, S = 25};
struct Vector2i
{
int x;
int y;
Vector2i() {}
Vector2i(int _x, int _y) : x(_x), y(_y) {}
};
struct Square
{
bool Data[W][H];;
Vector2i Origin = Vector2i(W / 2, H / 2);
void clear() {
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x)
Data[x][y] = false;
}
}
void setSquare() {
for (int y = H / 2 - S / 2; y < H / 2 + S / 2; ++y) {
for (int x = W / 2 - S / 2; x < W / 2 + S / 2; ++x)
Data[x][y] = true;
}
}
void draw() {
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
if (y == Origin.y && x == Origin.x) std::cout << '+'; //Marks the origin
else if (Data[x][y]) std::cout << 'X';
else std::cout << '.';
}
std::cout << '\n';
}
}
};
Vector2i oldPos(Vector2i new_, float theta) {
theta *= 3.14159265f / 180.f; //Converting from degrees to radians
return Vector2i(new_.x * cosf(theta) + new_.y * sinf(theta) + 0.5f,
new_.y * cosf(theta) - new_.x * sinf(theta) + 0.5f);
}
int main()
{
cout << "Enter an angle (in degrees): ";
float angle = 0;
cin >> angle;
Square One;
One.clear();
One.setSquare();
One.draw();
Square Two;
Two.clear();
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
Vector2i vec = oldPos(Vector2i(x - One.Origin.x, y - One.Origin.y), angle);
vec.x += One.Origin.x;
vec.y += One.Origin.y;
if (vec.x >= 0 && vec.x < W && vec.y >= 0 && vec.y < H)
Two.Data[x][y] = One.Data[vec.x][vec.y];
}
}
Two.draw();
return 0;
}
Well your problem has nothing to do with whether or not your are developing a console or GUI application. Images are stored and processed as matrices of pixels. When you rotate the image, the resulting position for a specific pixel is usually not integers.
The idea is to go the other way around.
You calculate the four corners of the rotated sqaure.
For each position(pixel) in the rotated square, you calculate its color by rotating it back to the original square.

Rotating image not working

I'm trying to rotate an image using openFrameworks, but I have a problem. My rotated image is red instead of its original color.
void testApp::setup(){
image.loadImage("abe2.jpg");
rotatedImage.allocate(image.width, image.height, OF_IMAGE_COLOR);
imageCenterX = image.getWidth() / 2;
imageCenterY = image.getHeight() / 2;
w = image.getWidth();
h = image.getHeight();
int degrees = 180;
float radians = (degrees*(PI / 180));
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int index = image.getPixelsRef().getPixelIndex(x, y);
int newX = (cos(radians) * (x - imageCenterX) - sin(radians) * (y - imageCenterY) + imageCenterX);
int newY = (sin(radians) * (x - imageCenterX) + cos(radians) * (y - imageCenterY) + imageCenterY);
int newIndex = rotatedImage.getPixelsRef().getPixelIndex(newX, newY);
rotatedImage.getPixelsRef()[newIndex] = image.getPixelsRef()[index];
}
}
rotatedImage.update();
}
void testApp::update(){
}
void testApp::draw(){
image.draw(0,0);
rotatedImage.draw(0,400);
}
Can someone tell me what I am doing wrong?
If your image has three color components (Red, Green, Blue), you need to transform all three of those. The following should do the trick:
rotatedImage.getPixelsRef()[newIndex] = image.getPixelsRef()[index];
rotatedImage.getPixelsRef()[newIndex+1] = image.getPixelsRef()[index+1];
rotatedImage.getPixelsRef()[newIndex+2] = image.getPixelsRef()[index+2];

Drawing tilemap is lowering my fps to a crawl

Okay, I'm trying to get my fps to 60, but right now it's at around 20. What can I do to this code to speed it up? Note: this is c++ using sfml.
App.Clear();
for(int x = 0; x < lv.width; x++){
for(int y = 0; y < lv.height; y++){
int tileXCoord = 0;
int tileYCoord = 0;
int tileSheetWidth = tilemapImage.GetWidth() / lv.tileSize;
if (lv.tile[x][y] != 0)
{
tileXCoord = lv.tile[x][y] % tileSheetWidth;
tileYCoord = lv.tile[x][y] / tileSheetWidth;
}
tilemap.SetSubRect(sf::IntRect(tileXCoord * lv.tileSize, tileYCoord * lv.tileSize, (tileXCoord * lv.tileSize) + lv.tileSize, (tileYCoord * lv.tileSize) + lv.tileSize));
tilemap.SetPosition(x * lv.tileSize, y * lv.tileSize);
App.Draw(tilemap);
}
}
playerSprite.SetSubRect(sf::IntRect(player.width * player.frame, player.height * player.state,
(player.width * player.frame) + player.width, (player.height * player.state) + player.height));
playerSprite.SetPosition(player.x, player.y);
App.Draw(playerSprite);
if(player.walking){
if(player.frameDelay >= 0)
player.frameDelay--;
if(player.frameDelay <= 0){
player.frame++;
player.frameDelay = 10;
if(player.frame >= 4)
player.frame = 0;
}
}
for(int x = 0; x < lv.width; x++){
for(int y = 0; y < lv.height; y++){
int tileXCoord = 0;
int tileYCoord = 0;
int tileSheetWidth = tilemapImage.GetWidth() / lv.tileSize;
if (lv.ftile[x][y] != 0)
{
tileXCoord = lv.ftile[x][y] % tileSheetWidth;
tileYCoord = lv.ftile[x][y] / tileSheetWidth;
}
tilemap.SetSubRect(sf::IntRect(tileXCoord * lv.tileSize, tileYCoord * lv.tileSize, (tileXCoord * lv.tileSize) + lv.tileSize, (tileYCoord * lv.tileSize) + lv.tileSize));
tilemap.SetPosition(x * lv.tileSize, y * lv.tileSize);
App.Draw(tilemap);
}
}
App.Display();
It looks like you're iterating over the pixels of your level, instead of over the tiles. Rewrite it like
///get the width of a tile
// get the height of a tile
int tileWidth = tilemapImage.getWidth();
int tileHeight = tilemapImage.getHeight();
//find the number of tiles vertically and horizontally, by dividing
// the level width by the number of tiles
int xTiles = lv.width / tileWidth;
int yTiles = lv.height / tileHeight();
for (int x = 0; x < xTiles; x++) {
for (int y = 0; y < yTiles; y++) {
// Do your calculations here
//ie: if(Walking) { draw_walk_anim; }
// draw_tile[x][y];
tilemap.SetPosition(x * tileWidth, y * tileHeight);
}
}
I lack expertise in the area, but you're drawing your tilemap for every tile, based on the parameters it's taking, it looks like it's redrawing the entire tilemap even though it's changed at most a single tile.
How would only calling App.Draw(tilemap); after every row, or perhaps after you've set the entire screen affect things.