Color change a background in processing w/ out affecting particles - background

I'm trying to fade a background in and out into different colors. I decided to try drawing a rect rather than using background, but I'm getting trails on my particles, because the background isn't getting drawn. Suggestions on how to fix this?
// main tab
ArrayList<ParticleSystem> systems;
PVector windRight = new PVector(0.1,0);
PVector sortaSpeed = new PVector(-0.1,0);
PVector gravity = new PVector(0,0.05);
boolean wR = false;
boolean sP = false;
boolean cS = false;
int limit = 8;
int alpha = 10;
color[] colorArray = {color(0,0,0,alpha),color(16, 37, 43,alpha),color(51, 10, 10,alpha),color(126, 255, 0,alpha)};
int currentColor;
int nextColor;
boolean change = false;
void setup() {
size(640,480);
systems = new ArrayList<ParticleSystem>();
smooth();
noStroke();
currentColor = 0;
for(int i = 0; i < limit; i++){
systems.add(new ParticleSystem(random(100,200),10,new PVector(random(100,500),-5))); //random(480)
}
background(0);
}
void draw() {
//rect(0, 0, 2000, 2000);
fill(colorArray[currentColor]);
rect(0, 0, width*2, height*2);
//background(colorArray[currentColor]);
if(change){
currentColor = nextColor;
change = false;
}
if(!systems.isEmpty()){
for (int i =0; i < systems.size(); i++){
ParticleSystem ps = systems.get(i);
ps.applyForce(gravity);
ps.run();
if(wR){
ps.applyForce(windRight);
}
if(sP){
ps.applyForce(sortaSpeed);
}
}
}
}
void keyPressed() {
if(key == 'w'){
wR = true;
print("w");
}
if(key == 'a'){
print('a');
sP = true;
}
}
void keyReleased(){
if(key == 'w'){
wR = false;
} else if(key == 'a'){
sP = false;
} else if(key == 's'){
if(key == 's'){
change = true;
println("currentColor: "+currentColor);
int newColor = currentColor;
while (newColor == currentColor)
newColor=(int) random(colorArray.length);
nextColor = newColor;
}
} // end of cS
}

In the future, please try to post an MCVE. Right now we can't run your code because it contains compiler errors. We don't need to see your entire sketch anyway though, just a small example that gets the point across.
But your problem is caused because you're trying to use alpha values in your background. That won't work with the background() function because that function ignores alpha values, and it won't work with the rect() function because then you won't be clearing out old frames- you'll see them through the transparent rectangle.
Instead, you could use the lerpColor() function to calculate the transition from one color to another over time.
Here's an example that transitions between random colors:
color fromColor = getRandomColor();
color toColor = getRandomColor();
float currentLerpValue = 0;
float lerpStep = .01;
void draw() {
color currentColor = lerpColor(fromColor, toColor, currentLerpValue);
currentLerpValue += lerpStep;
if (currentLerpValue >= 1) {
fromColor = currentColor;
toColor= getRandomColor();
currentLerpValue = 0;
}
background(currentColor);
}
color getRandomColor() {
return color(random(255), random(255), random(255));
}

Related

Ogmo Tilemap not showing in the game

So I am doing the haxe flixel TurnBasedRPG tutorial
I am pretty much a noob so I wont be surprised if this is just a stupid mistake I did.
But when I try to put my ogmo tilemap into the game, it doesnt show
Here is my Playstate.hx file
package;
import flixel.FlxG;
import flixel.FlxState;
import flixel.addons.editors.ogmo.FlxOgmo3Loader.EntityData;
import flixel.addons.editors.ogmo.FlxOgmo3Loader;
import flixel.tile.FlxTilemap;
class PlayState extends FlxState
{
var player:Player;
var map:FlxOgmo3Loader;
var walls:FlxTilemap;
override public function create()
{
map = new FlxOgmo3Loader(AssetPaths.HaxeFlixel_Tutorial__ogmo, AssetPaths.level_1__json);
walls = map.loadTilemap(AssetPaths.tiles__png, "walls");
walls.follow();
walls.setTileProperties(1, NONE);
walls.setTileProperties(2, ANY);
player = new Player();
map.loadEntities(placeEntities, "entities");
add(walls);
add(player);
super.create();
}
function placeEntities(entity:EntityData)
{
if (entity.name == "player")
{
player.setPosition(entity.x, entity.y);
}
}
override public function update(elapsed:Float)
{
super.update(elapsed);
FlxG.collide(player, walls);
}
}
Player.hx:
package;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.math.FlxPoint;
import flixel.util.FlxColor;
class Player extends FlxSprite
{
static inline var SPEED:Float = 200;
public function new(x:Float = 0, y:Float = 0)
{
super(x, y);
loadGraphic(AssetPaths.player__png, true, 16, 16);
drag.x = drag.y = 1600;
setSize(8, 8);
offset.set(4, 4);
setFacingFlip(LEFT, false, false);
setFacingFlip(RIGHT, true, false);
animation.add("lr", [3, 4, 3, 5], 6, false);
animation.add("u", [6, 7, 6, 8], 6, false);
animation.add("d", [0, 1, 0, 2], 6, false);
}
function updateMovement()
{
var up:Bool = false;
var down:Bool = false;
var left:Bool = false;
var right:Bool = false;
var newAngle:Float = 0;
right = FlxG.keys.anyPressed([RIGHT, D]);
down = FlxG.keys.anyPressed([DOWN, S]);
left = FlxG.keys.anyPressed([LEFT, A]);
up = FlxG.keys.anyPressed([UP, W]);
if (up || down || left || right)
{
if (up && down)
{
up = down = false;
}
if (left && right)
{
left = right = false;
}
if (up)
{
newAngle = -90;
if (left)
newAngle -= 45;
else if (right)
newAngle += 45;
facing = UP;
}
else if (down)
{
newAngle = 90;
if (left)
newAngle += 45;
else if (right)
newAngle -= 45;
facing = DOWN;
}
else if (left)
{
newAngle = 180;
facing = LEFT;
}
else if (right)
{
newAngle = 0;
facing = RIGHT;
}
// determine our velocity based on angle and speed
velocity.set(SPEED, 0);
velocity.rotate(FlxPoint.weak(0, 0), newAngle);
// if the player is moving (velocity is not 0 for either axis), we need to change the animation to match their facing
if ((velocity.x != 0 || velocity.y != 0) && touching == NONE)
{
switch (facing)
{
case LEFT, RIGHT:
animation.play("lr");
case UP:
animation.play("u");
case DOWN:
animation.play("d");
case _:
}
}
}
}
override function update(elapsed:Float)
{
updateMovement();
super.update(elapsed);
}
}
If you want to see any other file please ask me because I have been stuck on this for 3 hours now

Is there a way to use a bitmap or glide rather than a drawable image in MPAndroidChart?

int[] moodIconRes = {
R.drawable.ic_emoticon_01, R.drawable.ic_emoticon_02, R.drawable.ic_emoticon_03,
R.drawable.ic_emoticon_04, R.drawable.ic_emoticon_05, R.drawable.ic_emoticon_06,
R.drawable.ic_emoticon_07, R.drawable.ic_emoticon_08, R.drawable.ic_emoticon_09,
R.drawable.ic_emoticon_10, R.drawable.ic_emoticon_11, R.drawable.ic_emoticon_12
};
Right now I am using it as a drawable.
private void setData1(HashMap<Integer, Integer> hashMap) {
ArrayList entries = new ArrayList<>();
int totalCount = 0; // 총 기분 수 (전체, 올해, 이번달마다 달라지는 값이므로 호출마다 초기화)
maxMoodIndex = -1; // 제일 많은 기분 종류
maxCount = -1; // 제일 많은 기분의 개수
colors.clear(); // 파이차트를 구성할 색깔배열 clear (전체, 올해, 이번달마다 달라지는 값이므로 clear 필요)
for(int i = 0; i < 12; i++) {
int count = 0;
if(hashMap.containsKey(i)) {
count = hashMap.get(i);
setMoodCount(i, count);
totalCount += count;
addColor(i); // 기분 종류에 맞게 색깔 설정
entries.add(new PieEntry(
count,
"",
ContextCompat.getDrawable(requireContext(), moodIconRes[i])
));
} else {
setMoodCount(i, count); // 개수 0
}
}
I wonder if there is a way to call it in the form of a bitmap or r.id.imageview rather than a drawable image in this part. I'd appreciate it if someone could give me an idea.
You can use BitmapDrawable
Drawable d = new BitmapDrawable(getResources(), bitmap);

Set map borders to not cross inside the view area

I am trying to translate an old flash animation with animate. On the original flash animation the map image is draggable and zoomable but the map ´s borders always stick to the sides of the stage if you pan it or zoom it all the way.
On my test i grabbed some code that allows panning and zooming but the map crosses the stage boundaries if you pan all the way, in fact you can make the map dissapear of the stage.
I think there should be a way to draw like a secondary outer stage and not let the map image go beyond it.
This is the code I have.
var that = this;
var clickedX;
var clickedY;
var isDragging = false;
var friction = 0.85;
var speedX = 0;
var speedY = 0;
var mapOriginalX = this.map.x;
var mapOriginalY = this.map.y;
var mapNudge = 5;
var minScale = 0.25;
var maxScale = 3;
function onMouseWheel(e)
{
var delta;
if (e == window.event)
delta = -10 / window.event.wheelDeltaY;
else
delta = e.detail / 30;
var zoomFactor = delta;
scaleMap(zoomFactor);
}
function mouseDown(e)
{
clickedX = stage.mouseX;
clickedY = stage.mouseY;
isDragging = true;
console.log(stage.mouseX);
console.log(stage.mouseY);
}
function stageMouseUp(e)
{
isDragging = false;
}
function update(e)
{
if (isDragging)
{
speedX = stage.mouseX - clickedX;
speedY = stage.mouseY - clickedY;
}
speedX *= friction;
speedY *= friction;
// saber el tamaño actual del mapa en este punto.
that.map.x += speedX;
that.map.y += speedY;
console.log(that.map.y);
console.log(that.map.x);
clickedX = stage.mouseX;
clickedY = stage.mouseY;
//
}
function resetMap()
{
that.map.x = mapOriginalX;
that.map.y = mapOriginalY;
that.map.scaleX = that.map.scaleY = 1;
}
function zoomMap(e) //control visual
{
if (e.currentTarget == that.plusButton)
scaleMap(-0.1);
if (e.currentTarget == that.minusButton)
scaleMap(0.1);
}
function moveMap(e) //control visual
{
if (e.currentTarget == that.upButton)
speedY -= mapNudge;
else if (e.currentTarget == that.rightButton)
speedX += mapNudge;
else if (e.currentTarget == that.downButton)
speedY += mapNudge;
else if (e.currentTarget == that.leftButton)
speedX -= mapNudge;
}
function scaleMap(amount)
{
var map = that.map; // we will scale de map so this goes first.
map.scaleX -= amount; // same as map.scaleX = map.scaleX - amount
map.scaleY = map.scaleX;
if (map.scaleX < minScale)
map.scaleX = map.scaleY = minScale;
else if (map.scaleX > maxScale)
map.scaleX = map.scaleY = maxScale;
}
// listeners
this.map.on("mousedown", mouseDown.bind(this));
this.resetButton.on("click", resetMap.bind(this));
this.plusButton.on("click", zoomMap.bind(this));
this.minusButton.on("click", zoomMap.bind(this));
this.upButton.on("click", moveMap.bind(this));
this.rightButton.on("click", moveMap.bind(this));
this.downButton.on("click", moveMap.bind(this));
this.leftButton.on("click", moveMap.bind(this));
stage.on("stagemouseup", stageMouseUp.bind(this));
document.getElementById('canvas').addEventListener('mousewheel', onMouseWheel.bind(this));
document.getElementById('canvas').addEventListener('DOMMouseScroll', onMouseWheel.bind(this));
createjs.Ticker.addEventListener("tick", update.bind(this));
resetMap();
One trick I usually use is to create a "fence" procedure that checks bounds and corrects them. It will take some setup though.
To use this method, first set up these variables based on your own scene. Perhaps this is what you meant by defining a "second stage?"
var stageLeft = 0;
var stageRight = 500;
var stageTop = 0;
var stageBottom = 500;
this.map.setBounds(0,0,1462, 1047); // Set the values to match your map
var mapBounds = this.map.getBounds();
Then, add this procedure, or a variation of it based on how your map coordinates are set.
// procedure to correct the map x/y to fit the stage
function fenceMap() {
var map = that.map;
var ptTopLeft = map.localToGlobal(mapBounds.x,mapBounds.y);
var ptBotRight = map.localToGlobal(mapBounds.width,mapBounds.height);
if ((ptBotRight.x - ptTopLeft.x) > (stageRight-stageLeft)) {
if (ptTopLeft.x > stageLeft) {
map.x -= ptTopLeft.x - stageLeft;
speedX = 0;
} else if (ptBotRight.x < stageRight) {
map.x -= ptBotRight.x - stageRight;
speedX = 0;
}
}
if ((ptBotRight.y - ptTopLeft.y) > (stageBottom-stageTop)) {
if (ptTopLeft.y > stageTop) {
map.y -= ptTopLeft.y - stageTop;
speedY = 0;
} else if (ptBotRight.y < stageBottom) {
map.y -= ptBotRight.y - stageBottom;
speedY = 0;
}
}
}
Then, just add to the end of your update(), zoomMap(), moveMap(), and scaleMap() functions:
fenceMap();

ColorSpace Issues Migrating to PDFBox 2.0.x

Our department has inherited code that uses Apache PDFBox 1.8.x or earlier and we are in the process of trying to migrate it to Apache PDFBox 2.0.x.
I have resolved a lot of the various issues in this migration, but I'm still having problems migrating some of the ColorSpace related code. Below are some examples that I haven't figured out how to resolve. I've used the missing methods as the headings for each code snippet.
getColorSpaces() and setColorSpace()
public class ColorSpaceSetter extends OperatorProcessor {
private static final Logger logger = LogManager.getLogger(ColorSpaceSetter.class.getName());
public void process(Operator operator, List<COSBase> arguments) throws IOException {
try {
COSName arg = (COSName)arguments.get(0);
String argString = arg.getName();
if (context.getColorSpaces().containsKey(argString)) {
PDColorSpace colorSpace = context.getColorSpaces().get(argString);
if (colorSpace.getName().equals(COSName.SEPARATION.getName())) {
PDSeparation separation = (PDSeparation)colorSpace;
PDColor color;
//Non-stroking
if (StringUtils.isAllLowerCase(operator.getName())) {
color = context.getGraphicsState().getNonStrokingColor();
//Stroking
} else {
color = context.getGraphicsState().getStrokingColor();
}
color.setColorSpace(separation);
}
}
} catch (Exception e) {
logger.error("Unexpected argument array for operator " + operator.getName(), e);
}
}
}
getColorSpace()
public boolean determineStroking(PDColor color) {
for ( Float val : color.getColorSpace()) {
if (val != 1) {
return true;
}
}
return false;
}
setColorSpace() and setColorSpaceValue()
public class StrokeSetter extends OperatorProcessor {
public void process(Operator operator, List<COSBase> arguments) throws IOException {
//Supported operators are: g, rg, k, sc, and scn
//g = device gray (black or white)
//rg = rgb (000 is black, 111 is white, other is some other color)
//k = cmyk (0 is black, 1 is white, other is some other color)
//sc and scn = could be anything, but 0 is black, 1 is white)
boolean blackSeparation = false;
//Lowercase is non-stroking (fill) color
PDColor color;
if (StringUtils.isAllLowerCase(operator.getName())) {
color = context.getGraphicsState().getNonStrokingColor();
//Uppercase is stroking color
} else {
color = context.getGraphicsState().getStrokingColor();
}
//Treat separations differently - see section 4.5.5 of PDF Reference Documentation
PDColorSpace colorSpace = color.getColorSpace();
if (colorSpace.getName().equals(COSName.SEPARATION.getName())) {
PDSeparation separation = (PDSeparation)color.getColorSpace();
if (separation.getColorantName().equals("Black")) {
blackSeparation = true;
}
}
//Black and White
if (operator.getName().equalsIgnoreCase("g")) {
color.setColorSpace( new PDDeviceGray() );
float[] values = new float[1];
if ( arguments.size() >= 1 ) {
values[0] = ((COSNumber)arguments.get( 0 )).floatValue();
} else {
throw new IOException( "Error: Expected at least one argument when setting gray color");
}
color.setColorSpaceValue( values );
//RGB colors
} else if (operator.getName().equalsIgnoreCase("rg")) {
color.setColorSpace(PDDeviceRGB.INSTANCE);
float[] values = new float[3];
for ( int i = 0; i < arguments.size(); i++) {
values[i] = ((COSNumber)arguments.get( i )).floatValue();
}
color.setColorSpaceValue(values);
//CMYK colors
} else if (operator.getName().equalsIgnoreCase("k")) {
color.setColorSpace( PDDeviceCMYK.INSTANCE );
float[] values = new float[4];
for( int i=0; i<arguments.size(); i++ )
{
values[i] = ((COSNumber)arguments.get( i )).floatValue();
}
color.setColorSpaceValue(values);
// Unspecified ColorSpace
} else if (operator.getName().equalsIgnoreCase("sc") || operator.getName().equalsIgnoreCase("scn")) {
int size = arguments.size();
if ( size == 1) {
color.setColorSpace(new PDDeviceGray());
} else if ( size == 3) {
color.setColorSpace(PDDeviceRGB.INSTANCE);
} else if ( size == 4) {
color.setColorSpace(PDDeviceCMYK.INSTANCE);
} else {
color.setColorSpace(new PDDeviceN());
}
float[] values = new float[size];
for( int i=0; i<arguments.size(); i++ )
{
//Flip values when blackSeparation for PDDeviceGray
if (blackSeparation & size == 1) {
float val = ((COSNumber)arguments.get( i )).floatValue();
values[i] = Math.abs(val - 1);
} else {
values[i] = ((COSNumber)arguments.get( i )).floatValue();
}
}
color.setColorSpaceValue(values);
}
}
}

Error #2006: The supplied index is out of bounds

I keep getting
Error #2006: The supplied index is out of bounds.
at flash.display::DisplayObjectContainer/getChildAt()
at Main/onFrame()
This is mostly referring to this part of my code
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
My animation that I am pulling at the second frame also isn't running at all, though I have checked the symbol and the frames within it, and it should work fine. I'm pretty new to code and this is what I have been taught so far.
This is the rest of my code here.
We are supposed to make a basic game where our character walks to a power up and does a power up animation, followed by an end game title.
package
{
import flash.display.MovieClip;
import fl.motion.easing.Back;
import flash.sampler.Sample;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
var bg:Background;
var b:Bubbles;
var b2:Bubbles;
var s:Seaweed;
var pressingRight:Boolean = false;
var pressingLeft:Boolean = false;
var comp:Boolean = false;
var speed:int = 10;
var char:Character;
var pu:PowerUp;
var hit:hit1
var end:EndGame;
public function Main()
{
bg = new Background;
addChild(bg);
char = new Character();
addChild(char);
char.x = stage.stageWidth/2;
char.y = 488;
b = new Bubbles();
addChild(b);
b2 = new Bubbles();
addChild(b2);
b2.y = +b2.height;
s = new Seaweed();
addChild(s);
pu = new PowerUp();
addChild(pu);
pu.x = 200;
pu.y = 450;
pu.height = 50;
pu.scaleX = pu.scaleY;
pu.gotoAndStop("SPIN");
hit = new hit1;
addChild(hit);
hit.x = char.x
hit.y = char.y - 50
end = new EndGame();
end.x = stage.stageWidth/2;
end.y = stage.stageHeight/2;
stage.addEventListener(Event.ENTER_FRAME, onFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}//main()
public function onFrame(e:Event)
{
if (!comp)
//Bubble Movement
b.y -= 1;
b2.y -= 1;
if (b.y >= stage.stageHeight)
{
b.y = b2.y + bg.height;
}
else if (b2.y >= stage.stageHeight)
{
b2.y = b.y + b2.height;
}
//Background & Character Movement
if (pressingRight && char.x < stage.stageWidth/2)
{
char.x += speed * 0.4
}
else if (pressingRight == true && (bg.width + bg.x) > stage.stageWidth)
{
bg.x -= speed * 0.4;
s.x -= speed * 0.6;
pu.x -= speed * 0.4;
}
else if (pressingRight == true)
{
char.x += speed * 0.4;
}
if (pressingLeft == true && char.x > stage.stageWidth/2)
{
char.x -= speed * 0.4;
}
else if (pressingLeft == true && bg.x <0)
{
bg.x += speed * 0.4;
s.x += speed * 0.6;
pu.x += speed * 0.4;
}
else if (pressingLeft)
{
char.x -= speed * 0.4;
}
//Boundaries
if (char.x > stage.stageWidth)
{
char.x = stage.stageWidth;
}
else if (char.x < 0)
{
char.x = 0;
}
//Character Looking Directions
if (pressingLeft == true)
{
char.scaleX = -1;
hit.x = char.x
}
if (pressingRight == true)
{
char.scaleX = 1;
hit.x = char.x
}
//Character Movements
if (pressingRight || pressingLeft)
{
char.gotoAndStop("WALK");
}
else if (!pressingRight || !pressingLeft)
{
char.gotoAndStop("IDLE");
}
//Getting the Power up
if (pu.hitTestObject(hit))
{
char.gotoAndStop("POWER");
comp = true;
pu.gotoAndStop("GONE");
}
// !end
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
}
}//Comp
}//onFrame
public function keyPressed(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = true;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = true;
}
} // keyPressed()
public function keyReleased(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = false;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = false;
}
} // keyReleased()
}//public class()
}//package()
If you're using a language with zero-based indexing (where array indexes start at 0, not 1) Then this could be the problem.
Frame 1 would be at index [0] and frame 2 would be at index [1].
If you have 2 frames for example and try to access the frame at index[2] you are stepping beyond the bounds of your array and this is probably why you are getting that error message.