Changing opacity of each shape seperately in an array p5.js - arrays

I'm new to coding. I created a simple code and I need help with targeting each of the elements (each rectangle) in the array seperately. My goal is to change the opacity or transparency of each of the rectangles.
I can simply do fill(0, 255, 100, 50)and add an alpha value but this changes all of the rectangles..
I want to change the transparency - Alpha values: 50, 100, 150, 200, 250 respectively for each rectangle.
I tried to create an array for it and implement it to the rectangles but I can't seem to do it.
Here is the code, any help is appreciated :)
function setup() {
createCanvas(500, 110);
}
function draw() {
background(0, 100, 180);
stroke(2);
rectMode(CENTER);
for (var i = 0; i < 5; i++) {
fill(0,255, 100);
rect((i+1)*80, 50, 50, 50, 15);
}
}

You can dynamically define a color (including alpha attribute) using the color() function.
Here is a working example: https://editor.p5js.org/chen-ni/sketches/aWnKXEYh1
var alphaValues = [50, 100, 150, 200, 250];
function setup() {
createCanvas(500, 110);
}
function draw() {
background(0, 100, 180);
stroke(2);
rectMode(CENTER);
for (var i = 0; i < alphaValues.length; i++) {
var _alpha = alphaValues[i];
var _color = color(0, 255, 100, _alpha);
fill(_color);
rect((i + 1) * 80, 50, 50, 50, 15);
}
}

Related

Processing, initialised array added to constructor but not able to add it for the initialsed object

I am making a solar system simulator in Processing. I have initialsed an array in the Planet class which holdes the textures for the PShape planetary objects.
I have added this array to the constructor. Then I tried to call it in the main class where I have initialised the planets, but I get the following erros:
Main class: Syntax Error - Error on parametre or method declaration near 'void'?
Clearly I am missing something or done something wrong. Thank you for the reply.
// Solar_system_enginee main class
//Solar system and it's gravitation's simulation.
// The central sun applies gravitation to other celestial bodies
PImage background;
PImage sun_Texture;
float cameraX, cameraY;
// zoom and pan
float scale = 0.06;
float xPan = 600;
float yPan = 398;
boolean zoomIn = false;
boolean zoomOut = false;
//includes
Sun sun;
Planet mercury;
Planet venus;
Planet earth;
Planet mars;
Planet jupiter;
Planet saturn;
Planet uranus;
Planet neptune;
Planet pluto;
Planet _planetTextures
//screen setup
void setup() {
//Screen size
size(1200, 799, P3D);
sun_Texture = loadImage("sun.jpg");
// Celestial object properties
// 1; Planet's size
// 2; Planet's color / texture
// 3; Movement speed
// 4; Planet's path color
// 5; Planet's path size
// 6; Distance from Sun
// 7; Planet's number of moons // need to check it
//Spawn celestial objects
sun = new Sun(696, color(255, 50, 0));
mercury = new Planet(5, 0.2, 2, color(255, 200, 100), 1448, _planetTextures[0]);
venus = new Planet(12, 0.2, 2, color(150, 10, 100), 1499, _planetTextures[1]);
earth = new Planet(13, 0.2, 2, color(255, 255, 100, 100), 1540, _planetTextures[2]);
//mars = new Planet(7, 0.5, 2, color(167, 45, 160), 1618);
//jupiter = new Planet(143, 0.5, 2, color(167, 45, 160), 2169);
//saturn = new Planet(121, 0.5, 2, color(167, 45, 160), 2825);
//uranus = new Planet(51, 0.5, 2, color(167, 45, 160), 4263);
//neptune = new Planet(50,0.5, 2, color(167, 45, 160), 5886);
//pluto = new Planet(2, 0.5, 2, color(167, 45, 160), 6486);
}
// sceene setup
void sceene() {
// Load background image
background = loadImage("stars.jpg");
background(background);
// Set it in the middle of the screen
translate(width/2, height/2, 0);
}
// draw setup
void draw() {
// Zoom towards the center of the screen, rather the edge of the screen
translate(width/2, height/2, 0);
scale(scale);
// Translate Y and X pan
translate( -xPan, -yPan);
// Draw background
sceene();
// Zoom In
if (zoomIn) {
scale *= 1.01;
}
// Zoom Out
if (zoomOut) {
scale /= 1.01;
}
// Display sun and rotate Y axis camera around sun
sun.display();
sun.move(mouseY);
//mercury
mercury.display();
mercury.move();
//venus
venus.display();
venus.move();
//earth
earth.display();
earth.move();
////mars
//mars.display();
//mars.move();
////jupiter
//jupiter.display();
//jupiter.move();
////saturn
//saturn.display();
//saturn.move();
////uranus
//uranus.display();
//uranus.move();
////neptune
//neptune.display();
//neptune.move();
////pluto
//pluto.display();
//pluto.move();
}
// Key press record function, responsible for zoom in and out of scene
void keyPressed() {
if (keyCode == UP) {
zoomIn = true;
zoomOut = false;
}
if (keyCode == DOWN) {
zoomIn = false;
zoomOut = true;
}
}
void keyReleased() {
if (keyCode == UP) {
zoomIn = false;
}
if (keyCode == DOWN) {
zoomOut = false;
}
}
// Planets class
class Planet {
float radius = 0;
float moveSpeed;
float distance;
float size;
color planetColor;
int pathSize;
color pathColor;
PShape planet;
PImage[] planetTextures = new PImage [3];
Moon moon;
Planet(int _size, float _speed, int _path_size, color _path_color, float _dist, PImage[] _planetTextures) { //color _color
size = _size;
//planetColor = _color;
moveSpeed = _speed;
pathColor = _path_color;
pathSize = _path_size;
distance = _dist;
planetTextures = _planetTextures;
moon = new Moon(10, color(200, 200, 100));
// Set planet's texture
noStroke();
noFill();
planet = createShape(SPHERE, size);
planet.setTexture(_planetTextures[0]);
// Load textures into an array
planetTextures[0] = loadImage ("mercury.jpg");
planetTextures[1] = loadImage ("venus.jpg");
planetTextures[2] = loadImage ("earth.jpg");
}
void display() {
pushMatrix();
//path
stroke(pathColor);
strokeWeight(2);
noFill();
rotateY(radius * moveSpeed);
rotateX(PI/2);
ellipse(0, 0, 2*distance, 2*distance);
//body
noStroke();
fill(planetColor);
translate(distance, 0, 0);
shape(planet);
//sphere(size);
moon.display();
moon.move();
popMatrix();
}
void move() {
radius += moveSpeed;
}
}
The Syntax Error - Missing name or ; near ‘void’? error occurs between Planet _planetTextures and void setup().
Sometimes error can be a bit cryptic: in this case it's as straightforward as it can be: you forgot to add ; at the end of Planet _planetTextures.
That being said, I've spotted a bunch of other areas in your code you might want to revise:
_planetTextures is later used as if it's a PImage[] in setup() when you instantiate planets
the Planet constructor takes in a PImage[] _planetTextures argument. If a single planet uses a single texture, maybe you meant PImage _planetTexture instead ?
The Planet constructor loads 3 images (mercury, venus, earth): should it be task of the main sketch to load all assets, then pass each single PImage to it's respective planet (instead of reloading the same 3 images for every single planet instance)
since the planet texture is only once in the constructor, there's no need for the PImage[] property
the backround PImage was loaded continously, multiple times per frame in sceene() (called from draw()): you might want to load the image once in setup.
Here is your code with the above tweaks applied:
//Solar system and it's gravitation's simulation.
// The central sun applies gravitation to other celestial bodies
PImage background;
PImage sun_Texture;
float cameraX, cameraY;
// zoom and pan
float scale = 0.06;
float xPan = 600;
float yPan = 398;
boolean zoomIn = false;
boolean zoomOut = false;
//includes
Sun sun;
Planet mercury;
Planet venus;
Planet earth;
Planet mars;
Planet jupiter;
Planet saturn;
Planet uranus;
Planet neptune;
Planet pluto;
PImage[] planetTextures;
//screen setup
void setup() {
//Screen size
size(1200, 799, P3D);
sun_Texture = loadImage("sun.jpg");
// Celestial object properties
// 1; Planet's size
// 2; Planet's color / texture
// 3; Movement speed
// 4; Planet's path color
// 5; Planet's path size
// 6; Distance from Sun
// 7; Planet's number of moons // need to check it
// Load background image
background = loadImage("stars.jpg");
// Load textures into an array
planetTextures[0] = loadImage ("mercury.jpg");
planetTextures[1] = loadImage ("venus.jpg");
planetTextures[2] = loadImage ("earth.jpg");
//Spawn celestial objects
sun = new Sun(696, color(255, 50, 0));
mercury = new Planet(5, 0.2, 2, color(255, 200, 100), 1448, planetTextures[0]);
venus = new Planet(12, 0.2, 2, color(150, 10, 100), 1499, planetTextures[1]);
earth = new Planet(13, 0.2, 2, color(255, 255, 100, 100), 1540, planetTextures[2]);
//mars = new Planet(7, 0.5, 2, color(167, 45, 160), 1618);
//jupiter = new Planet(143, 0.5, 2, color(167, 45, 160), 2169);
//saturn = new Planet(121, 0.5, 2, color(167, 45, 160), 2825);
//uranus = new Planet(51, 0.5, 2, color(167, 45, 160), 4263);
//neptune = new Planet(50,0.5, 2, color(167, 45, 160), 5886);
//pluto = new Planet(2, 0.5, 2, color(167, 45, 160), 6486);
}
// sceene setup
void scene() {
background(background);
// Set it in the middle of the screen
translate(width/2, height/2, 0);
}
// draw setup
void draw() {
// Zoom towards the center of the screen, rather the edge of the screen
translate(width/2, height/2, 0);
scale(scale);
// Translate Y and X pan
translate( -xPan, -yPan);
// Draw background
scene();
// Zoom In
if (zoomIn) {
scale *= 1.01;
}
// Zoom Out
if (zoomOut) {
scale /= 1.01;
}
// Display sun and rotate Y axis camera around sun
sun.display();
sun.move(mouseY);
//mercury
mercury.display();
mercury.move();
//venus
venus.display();
venus.move();
//earth
earth.display();
earth.move();
////mars
//mars.display();
//mars.move();
////jupiter
//jupiter.display();
//jupiter.move();
////saturn
//saturn.display();
//saturn.move();
////uranus
//uranus.display();
//uranus.move();
////neptune
//neptune.display();
//neptune.move();
////pluto
//pluto.display();
//pluto.move();
}
// Key press record function, responsible for zoom in and out of scene
void keyPressed() {
if (keyCode == UP) {
zoomIn = true;
zoomOut = false;
}
if (keyCode == DOWN) {
zoomIn = false;
zoomOut = true;
}
}
void keyReleased() {
if (keyCode == UP) {
zoomIn = false;
}
if (keyCode == DOWN) {
zoomOut = false;
}
}
class Planet {
float radius = 0;
float moveSpeed;
float distance;
float size;
color planetColor;
int pathSize;
color pathColor;
PShape planet;
Moon moon;
Planet(int _size, float _speed, int _path_size, color _path_color, float _dist, PImage _planetTexture) { //color _color
size = _size;
//planetColor = _color;
moveSpeed = _speed;
pathColor = _path_color;
pathSize = _path_size;
distance = _dist;
moon = new Moon(10, color(200, 200, 100));
// Set planet's texture
noStroke();
noFill();
planet = createShape(SPHERE, size);
planet.setTexture(_planetTexture);
}
void display() {
pushMatrix();
//path
stroke(pathColor);
strokeWeight(2);
noFill();
rotateY(radius * moveSpeed);
rotateX(PI/2);
ellipse(0, 0, 2*distance, 2*distance);
//body
noStroke();
fill(planetColor);
translate(distance, 0, 0);
shape(planet);
//sphere(size);
moon.display();
moon.move();
popMatrix();
}
void move() {
radius += moveSpeed;
}
}
It would've made it easier to for others to test if you would have also posted the Sun/Moon classes and the textures uses: something to remember for future posts. (The easier it is for others to replicate your issue the more like to get (good) answers).
Not bad progress and you're getting the main points about classes.
There might still be confusion over how arguments get passed from the sketch(global) scope to instances, but that may also be an artefact of perhaps trying to write a lot of code in one go ?
If that's the case, I recommend slowing down, writing one bit of functionality at a time (e.g. one function or class method at a time, running the sketch and testing to ensure it works as expected first). Once a bit of code works as expected to you can move to the next and ideally text combinations of the newly added functionalities to ensure that there no weird interactions between classes. Constantly testing how the code behaves may appear slower, but resting assured the code works as go along is faster on the long run and it definitely makes debugging much easier (likely to be most recently added functionality which is also freshes in your memory). Have fun coding !

2D Raylib Texture Collisions

I was wondering how to properly handle collisions in Raylib. After setting up the basics, like a window, I would first load in the player texture, like so:
Texture2D playerTexture = LoadTexture("Player.png");
After that, I would draw the texture, with the Raylib function DrawTextureEx which allows me to adjust the rotation and scale of the texture. Then, I would add a simple movement script for the player, and that would be pretty much it.
As for collisions, I would just be testing the player collision on a rectangle. To get the area for the rectangle, I would just create a simple Rectangle struct like this:
Rectangle rect1 = {100, 100, 50, 50};
As for getting the player area, I would make something similar:
Rectangle playerArea = {player.x, player.y, playerTexture.width*player.scale, playerTexture.height*player.scale} //Values are stored in Player struct
However, when I try to check the collisons like this, nothing happens:
if (CheckCollisionRecs(playerArea, rect1)) {
DrawText("Collided", 5, 5, 25, BLACK);
}
Here's my full code, if needed:
#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 1200
#define HEIGHT 800
typedef struct {
const int width;
const int height;
int FPS;
} Window;
Window window = {
.FPS = 60,
};
typedef struct {
Vector2 pos;
Vector2 acc;
Vector2 vel;
int width;
int height;
double accSpeed;
int maxVel;
double friction;
double rotation;
double scale;
} Player;
Player player = {
.pos = {WIDTH/2, HEIGHT/2},
.acc = {0, 0},
.vel = {0, 0},
.width = 25,
.height = 25,
.accSpeed = 0.15,
.maxVel = 7,
.friction = 0.2,
.rotation = 0,
.scale = 0.5,
};
void movePlayer();
int rectCollide();
int main() {
InitWindow(WIDTH, HEIGHT, "Window");
SetTargetFPS(window.FPS);
Texture2D playerImg = LoadTexture("Player.png");
Rectangle playerArea = {player.pos.x, player.pos.y, playerImg.width*player.scale, playerImg.height*player.scale};
Rectangle rect1 = {100, 100, 50, 50};
Camera2D camera = { 0 };
camera.target = (Vector2){ player.pos.x + 20.0f, player.pos.y + 20.0f };
camera.offset = (Vector2){WIDTH/2.0f, HEIGHT/2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f;
if (CheckCollisionRecs(playerArea, rect1)) {
DrawText("Collided", 5, 5, 25, BLACK);
}
while (!WindowShouldClose()) {
BeginDrawing();
ClearBackground(SKYBLUE);
movePlayer();
camera.target = (Vector2){ player.pos.x + 20, player.pos.y + 20 };
BeginMode2D(camera);
DrawRectangle(100, 100, 50, 50, BLACK);
DrawTextureEx(playerImg, player.pos, player.rotation, player.scale, RAYWHITE);
EndMode2D();
EndDrawing();
}
UnloadTexture(playerImg);
CloseWindow();
return 0;
}
void movePlayer() {
if (IsKeyDown(KEY_LEFT) && player.vel.x > -player.maxVel) {
player.acc.x = -player.accSpeed;
} else if (IsKeyDown(KEY_RIGHT) && player.vel.x < player.maxVel) {
player.acc.x = player.accSpeed;
} else if (abs(player.vel.x) > 0.2) {
if (player.vel.x < 0) {
player.acc.x = player.friction;
} else {
player.acc.x = -player.friction;
}
} else {
player.vel.x = 0;
player.acc.x = 0;
}
player.vel.x += player.acc.x;
player.pos.x += player.vel.x;
if (IsKeyDown(KEY_UP) && player.vel.y > -player.maxVel) {
player.acc.y = -player.accSpeed;
} else if (IsKeyDown(KEY_DOWN) && player.vel.x < player.maxVel) {
player.acc.y = player.accSpeed;
} else if (abs(player.vel.y) > 0.2) {
if (player.vel.y < 0) {
player.acc.y = player.friction;
} else {
player.acc.y = -player.friction;
}
} else {
player.vel.y = 0;
player.acc.y = 0;
}
player.vel.y += player.acc.y;
player.pos.y += player.vel.y;
}
int rectCollide(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {
return x1 + w1 > x2 && x1 < x2 + w2 && y1 + h1 > y2 && y1 < y2 + h2;
}
And so, I was wondering: first of all, is there a better way to get the area of the texture, without having to create a Rectangle struct for each texture, and multiply the scale by the texture width and height? Secondly, I was wondering why my collisions aren't being detected. What is wrong with my code?
The collision check
if (CheckCollisionRecs(playerArea, rect1))
precedes the event loop.
Even moving it inside the loop will not have any effect, as playerArea is never updated in your event loop.
A quick fix would be to update the collision box after moving the player.
(example snippet of main, without images)
Rectangle playerArea;
Rectangle rect1 = {100, 100, 50, 50};
while (!WindowShouldClose()) {
movePlayer();
playerArea = (Rectangle) {
player.pos.x,
player.pos.y,
player.width,
player.height,
};
camera.target = (Vector2){ player.pos.x + 20, player.pos.y + 20 };
BeginDrawing();
ClearBackground(SKYBLUE);
BeginMode2D(camera);
DrawRectangleRec(rect1, RED);
DrawRectangle(player.pos.x, player.pos.y, player.width, player.height, RAYWHITE);
EndMode2D();
if (CheckCollisionRecs(playerArea, rect1))
DrawText("Collided", 5, 5, 25, BLACK);
EndDrawing();
}

convert sine-waves package examples to react component

I'm trying to use sine-waves package sine-waves package , in react app, first thing I did is looking for examples, border wave particularly and start to convert it to react component and when I tried to start the app, it gives me this error :
is there a problem in canvas with react
any help will be appreciated ...
this is my attempt:
import React from 'react';
import SineWaves from 'sine-waves';
import _ from 'lodash';
class SineWave extends React.Component {
width = 300;
height = 300;
amplitude = 20;
speed = 1;
ease = 'SineInOut';
waves = [
{
timeModifer: 2,
lineWidth: 1,
amplitude: this.amplitude,
wavelength: 100,
segmentLength: 1,
strokeStyle: 'rgba(255, 255, 255, 0.3333)',
type: 'Sawtooth',
},
{
timeModifer: 2,
lineWidth: 1,
amplitude: -this.amplitude / 2,
wavelength: 100,
segmentLength: 1,
strokeStyle: 'rgba(255, 255, 255, 0.3333)',
type: 'Sawtooth',
},
{
timeModifer: 2,
lineWidth: 1,
amplitude: -this.amplitude,
wavelength: 100,
segmentLength: 1,
strokeStyle: 'rgba(255, 255, 255, 0.3333)',
type: 'Square',
},
];
render() {
const { speed, width, height, ease, waves } = this;
const bottomWaves = new SineWaves({
el: document.getElementById('bottom-waves'),
speed,
width,
height,
ease,
waves: _.clone(waves, true),
rotate: 0,
resizeEvent() {
let gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
let index = -1;
let { length } = this.waves;
while (++index < length) {
this.waves[index].strokeStyle = gradient;
}
// Clean Up
index = void 0;
length = void 0;
gradient = void 0;
},
});
const topWaves = new SineWaves({
el: document.getElementById('top-waves'),
speed: -speed,
width,
height,
ease,
waves: _.clone(waves, true),
rotate: 0,
resizeEvent() {
let gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
let index = -1;
let { length } = this.waves;
while (++index < length) {
this.waves[index].strokeStyle = gradient;
}
// Clean Up
index = void 0;
length = void 0;
gradient = void 0;
},
});
const leftWaves = new SineWaves({
el: document.getElementById('left-waves'),
speed,
width: height,
height: width,
ease,
waves: _.clone(waves, true),
rotate: 90,
resizeEvent() {
let gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
let index = -1;
let { length } = this.waves;
while (++index < length) {
this.waves[index].strokeStyle = gradient;
}
// Clean Up
index = void 0;
length = void 0;
gradient = void 0;
},
});
const rightWaves = new SineWaves({
el: document.getElementById('right-waves'),
speed: -speed,
width: height,
height: width,
ease,
waves: _.clone(waves, true),
rotate: 90,
resizeEvent() {
let gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
gradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
let index = -1;
let { length } = this.waves;
while (++index < length) {
this.waves[index].strokeStyle = gradient;
}
// Clean Up
index = void 0;
length = void 0;
gradient = void 0;
},
});
return (
<>
<h1 id="title">
SineWaves.js
</h1>
<h2 id="sub-title">Border Example</h2>
<div id="box">
<h2 id="example-title">Animated Borders</h2>
<canvas className="wave" id="top-waves" />
<canvas className="wave" id="left-waves" />
<canvas className="wave" id="bottom-waves" />
<canvas className="wave" id="right-waves" />
</div>
</>
);
}
}
export default SineWave;
Generally speaking a message like
uncaught : No Canvas Selected would either mean you didn't specify a canvas target at all or it simply can't find it because it doesn't exist.
Looking at the parameters you're passing to the constructor of SineWaves
const rightWaves = new SineWaves({
el: document.getElementById('right-waves'),
you're telling it to look for a <canvas> element with the id right-waves.
Try setting one up like:
<canvas id="right-waves"></canvas>

WriteableBitmapEx alpha blend color issue

I'm trying to use WriteableBitmap with the WriteableBitmapEx extension methods. The code sample is below along with two screenshots. The first screenshot is what my code generates and the second what I'm expecting (hand drawn via Paint.Net).
Am I using WriteableBitmapEx incorrectly, misunderstanding how it works or is it a bug?
This is on .Net 4.6.1 and WriteableBitmapEx 1.6.2.
public MainWindow()
{
InitializeComponent();
_bitmap = BitmapFactory.New(1000, 1000);
_bitmap.FillRectangle(0,0,1000,1000, ColorToInt(Colors.White), true);
_bitmap.FillRectangle(100, 100, 500, 500, ColorToInt(_color), true);
_bitmap.FillRectangle(150, 150, 550, 550, ColorToInt(_color), true);
_bitmap.FillRectangle(200, 200, 600, 600, ColorToInt(_color), true);
_bitmap.FillRectangle(250, 250, 650, 650, ColorToInt(_color), true);
_bitmap.FillRectangle(300, 300, 700, 700, ColorToInt(_color), true);
_bitmap.FillRectangle(350, 350, 750, 750, ColorToInt(_color), true);
_bitmap.FillRectangle(400, 400, 800, 800, ColorToInt(_color), true);
Image1.Source = _bitmap;
}
private readonly Color _color = Color.FromArgb(25, 0, 0, 255);
private WriteableBitmap _bitmap;
private int ColorToInt(Color c)
{
return c.A << 24 | c.R << 16 | c.G << 8 | c.B;
}
The WriteableBitmap uses pre-multiplied alpha internally, so when you convert a color you have to take that into account and multiply your color channels with alpha.
You can simply use the ConvertColor method that comes with WBX or roll your own similar to this:
public static int ConvertColor(Color color)
{
var col = 0;
if (color.A != 0)
{
var a = color.A + 1;
col = (color.A << 24)
| ((byte)((color.R * a) >> 8) << 16)
| ((byte)((color.G * a) >> 8) << 8)
| ((byte)((color.B * a) >> 8));
}
return col;
}

SDL and C keyboard or touch event

I'm programming in c4droid but I can't get the touch event to work.
Tried switch or if statement but nothing works im sure rendering is ok because if I delete the switch then its renders normally
Here I the code:
#include <SDL2/SDL.h>
int main()
{
SDL_Window *window = NULL;
window = SDL_CreateWindow("Shooter", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
// Setup renderer
SDL_Renderer *renderer = NULL;
renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED);
// Set render color to red ( background will be rendered in this color )
SDL_SetRenderDrawColor(renderer, 0, 255, 25, 255);
// Clear winow
SDL_RenderClear(renderer);
// Creat a rect at pos ( 50, 50 ) that's 50 pixels wide and 50 pixels
// high.
SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255);
SDL_Rect r;
r.x = 500;
r.y = 500;
r.w = 50;
r.h = 50;
SDL_Rect e;
e.x = 5;
e.y = 5;
e.w = 50;
e.h = 50;
SDL_Event event;
while(SDL_PollEvent(&event) != 0) {
switch (event.type) {
case SDL_FINGERDOWN :
e.x = e.x + 10;
SDL_RenderFillRect(renderer, &r);
SDL_RenderFillRect(renderer, &e);
SDL_RenderPresent(renderer);
break;
}
}
// Wait for 5 sec
SDL_Delay(50000);
SDL_DestroyWindow(window);
SDL_Quit();
}
You need to make sure to poll the event.
while(true) {
while(SDL_PollEvent(&event) != 0) {
switch (event.type) {
case SDL_FINGERDOWN :
e.x = e.x + 10;
SDL_RenderFillRect(renderer, &r);
SDL_RenderFillRect(renderer, &e);
SDL_RenderPresent(renderer);
break;
// Render rect
}
}
}
Provided event is not NULL, SDL_PollEvent will take the next event from the queue and store it in the SDL_Event that event is pointing at.
Edit: Don't remove the while(true) loop, put this one inside it. Sorry, I probably should have been a bit more clear in the beginning.

Resources