minecraft 1.8 gui slider issues - user-interface

I recently started making a minecraft mod and i have a question regarding GUI's I want to create a slide, the only issue is the ButtonList.add(new GUISlider());
I don't understand the parameters, can someone explain them to me?
Thanks! :D

ok, I figured it out, you need to create a separate slider other than the default, then call it from there.
My Slider Code:
package tutorial.generic;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.opengl.GL11;
public class GuiSliderFixed extends GuiButton {
public float sliderValue = 1.0F;
public float sliderMaxValue = 1.0F;
public float sliderMinValue = 1.0F;
public boolean dragging = false;
public String label;
public GuiSliderFixed(int id, int x, int y, String label, float startingValue, float maxValue, float minValue) {
super(id, x, y, 150, 20, label);
this.label = label;
this.sliderValue = startingValue;
this.sliderMaxValue = maxValue;
this.sliderMinValue = minValue;
}
protected int getHoverState(boolean par1) {
return 0;
}
#Override
public void drawButton(Minecraft mc, int mouseX, int mouseY)
{
if (this.visible)
{
FontRenderer fontrenderer = mc.fontRendererObj;
mc.getTextureManager().bindTexture(buttonTextures);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.hovered = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height;
int k = this.getHoverState(this.hovered);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.blendFunc(770, 771);
this.drawTexturedModalRect(this.xPosition, this.yPosition, 0, 46 + k * 20, this.width / 2, this.height);
this.drawTexturedModalRect(this.xPosition + this.width / 2, this.yPosition, 200 - this.width / 2, 46 + k * 20, this.width / 2, this.height);
this.mouseDragged(mc, mouseX, mouseY);
int l = 14737632;
if (packedFGColour != 0)
{
l = packedFGColour;
}
else if (!this.enabled)
{
l = 10526880;
}
else if (this.hovered)
{
l = 16777120;
}
this.drawCenteredString(fontrenderer, this.displayString, this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, l);
}
}
protected void mouseDragged(Minecraft par1Minecraft, int par2, int par3) {
if (this.enabled && this.visible && this.packedFGColour == 0) {
if (this.dragging) {
this.sliderValue = (float) (par2 - (this.xPosition + 4)) / (float) (this.width - 8);
if (this.sliderValue < 0.0F) {
this.sliderValue = 0.0F;
}
if (this.sliderValue > 1.0F) {
this.sliderValue = 1.0F;
}
}
this.displayString = label + ": " + (int) (sliderValue * sliderMaxValue);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20);
this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20);
}
}
public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) {
if (super.mousePressed(par1Minecraft, par2, par3)) {
this.sliderValue = (float) (par2 - (this.xPosition + 4)) / (float) (this.width - 8);
if (this.sliderValue < 0.0F) {
this.sliderValue = 0.0F;
}
if (this.sliderValue > 1.0F) {
this.sliderValue = 1.0F;
}
this.dragging = true;
return true;
} else {
return false;
}
}
public void mouseReleased(int par1, int par2) {
this.dragging = false;
}
}
My GUI Code:
package tutorial.generic;
import java.awt.Color;
import java.io.IOException;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSlider;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
public class guiGenericTileEntity extends GuiScreen{
public static NBTTagCompound nameTag = new NBTTagCompound();
private int x, y, z;
private EntityPlayer player;
private World world;
private int xSize, ySize;
public static GuiTextField textField;
public static GuiSliderFixed mySlider;
public static NBTTagCompound maxSpeedTag = new NBTTagCompound();
public guiGenericTileEntity(EntityPlayer player, World world, int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
this.player = player;
this.world = world;
xSize = 176;
ySize = 214;
}
private ResourceLocation backgroundimage = new ResourceLocation(Generic.MODID.toLowerCase() + ":" + "textures/gui/guiBackGenericTileEntity.png");
#Override
public void drawScreen(int mouseX, int mouseY, float renderPartialTicks) {
this.mc.getTextureManager().bindTexture(backgroundimage);
int x = (this.width - xSize) / 2;
int y = (this.height - ySize) / 2;
drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
fontRendererObj.drawString("MTTA System", (int) (width / 2 - (width / 13)), height / 15, 8);
fontRendererObj.drawString("Train Name :", (int) (width / 2 - (width / 13)), (int) (height / 7.8), 8);
fontRendererObj.drawString("Max Speed :", (int) (width / 2 - (width / 13)), (int) (height / 3.5), 8);
textField.drawTextBox();
super.drawScreen(mouseX, mouseY, renderPartialTicks);
}
#Override
public boolean doesGuiPauseGame() {
return false;
}
#Override
public void updateScreen(){
textField.updateCursorCounter();
super.updateScreen();
}
#Override
protected void keyTyped(char typedChar, int keyCode) throws IOException{
textField.textboxKeyTyped(typedChar, keyCode);
super.keyTyped(typedChar, keyCode);
}
#Override
public void initGui(){
buttonList.add(new GuiButton(1, (int) (xSize / 3 * 2.35), ySize - (ySize / 18), xSize - 20, height / 12, "Save And Close"));
mySlider = new GuiSliderFixed(3, width / 2 - 75, height / 3, "MPH ", 1.0F, 100.0F, 1.0F);
buttonList.add(mySlider);
mySlider.sliderValue = maxSpeedTag.getFloat("MaxSpeed");
textField = new GuiTextField(width / 2, fontRendererObj, width / 2 - 50, (int) (height / 6), 100, 20);
textField.setMaxStringLength(30);
textField.setText(nameTag.getString("Name"));
textField.setFocused(true);
textField.setCanLoseFocus(false);
super.initGui();
}
#Override
protected void actionPerformed(GuiButton guibutton) {
//id is the id you give your button
switch(guibutton.id) {
case 1:
player.closeScreen();
nameTag.setString("Name", textField.getText());
maxSpeedTag.setFloat("MaxSpeed", mySlider.sliderValue);
genericTileEntity.processActivate(player, world);
player.addChatMessage(new ChatComponentText("Saved the current settings for " + textField.getText() + "!"));
break;
}
//Packet code here
//PacketDispatcher.sendPacketToServer(packet); //send packet
}
}
Calling the new Slider works like this:
create a new GuiSliderFixed in the GUI code ---> example: ---> GuiSliderFixed mySlider = new GuiSliderFixed();
set the Parameters to this (int id, int x, int y, String label, float statingValue, float maxValue, float minValue) ---> example: ---> GuiSliderFixed mySlider = new GuiSliderFixed(3, width / 2 - 75, height / 3, "MPH ", 1.0F, 100.0F, 1.0F);
add it to buttonList ---> example ---> buttonList.add(mySlider);
Hope This Helps!

Related

Tried to make 3 moving parts of a screensaver in Processing, got one super fast part. Any ideas?

I created a screensaver that bounces around the screen. I tried to fit original the code into OOP (which I'm terrible at) so that I could have multiple versions of it bouncing around. Instead, I'm getting one instance travelling at an unusually fast speed.
How can I get instance1, instance2 and instance3 to be seperate instead of combining into one?
Notes:
In the class screenSavers, C stands for constructor parameter to differentiate from the original variables at the top. CS stands for class-specific to avoid confusion with the original variables at the top. (yes, it's confusing. I don't know why I did that)
GIANT WALL OF CODE ALERT
import java.lang.Math;
//defining dimensions and initial coords for the laptop frame
float frameW = 120;
float frameH = frameW * 3.0/4.0;
float frameX = random(frameW * 2, width);
float frameY = random(frameW * 2, height);
//defining variables are used in the movement of the laptop
float xSpeed = random(frameW / 50,frameH / 15);
float ySpeed = random(2,5);
boolean moveLeft = false;
boolean moveUp = false;
//defining the colours used in the program, as well as the alpha and stroke widths
int alpha = 255;
color baseColor = color(random(100, 255), random(100, 255), random(100, 255), alpha);
color accentColor = color(random(100, 255), random(100, 255), random(100, 255), alpha);
color baseColorAlpha;
color accentColorAlpha;
color bgColor = 0;
color outline = 255;
int outerCircleWeight = 5;
int laptopStrokeWeight = 1;
//initial states of little ellipses on the screen
float startingPoint = 7.5;
float leftDotRaise = 0;
boolean leftDown = false;
float centerDotRaise = 0;
boolean centerDown = false;
float rightDotRaise = 0;
boolean rightDown = false;
//variable for the radian at which the circles outside the laptop are at
float circleOrbit;
//variable for roundness of any initially circular shapes (ellipses, orbits, etc)
float specialRadii = 200;
//square-ification button
int buttonX = 200;
int buttonY = 200;
boolean buttonState = true;
int buttonTextSize = 30;
String offMessage = "Revert";
String onMessage = "Squarify";
String buttonMessage = onMessage;
public class screenSavers {
float frameWCS;
float xSpeedCS;
float ySpeedCS;
boolean moveLeftCS;
boolean moveUpCS;
int alphaCS;
color baseColorCS;
color accentColorCS;
color bgColorCS;
color outlineCS;
int outerCircleWeightCS;
int laptopStrokeWeightCS;
float startingPointCS;
float leftDotRaiseCS;
boolean leftDownCS;
float centerDotRaiseCS;
boolean centerDownCS;
float rightDotRaiseCS;
boolean rightDownCS;
float specialRadiiCS;
int buttonXCS;
int buttonYCS;
boolean buttonStateCS;
int buttonTextSizeCS;
String offMessageCS;
String onMessageCS;
String buttonMessageCS;
float circleOrbitCS;
public screenSavers (float frameWC, float xSpeedC, float ySpeedC, boolean moveLeftC, boolean moveUpC, int alphaC, color bgColorC, color outlineC, int outerCircleWeightC, int laptopStrokeWeightC, float startingPointC, float leftDotRaiseC, boolean leftDownC, float centerDotRaiseC, boolean centerDownC, float rightDotRaiseC, boolean rightDownC, float specialRadiiC, int buttonXC, int buttonYC, boolean buttonStateC, int buttonTextSizeC, String offMessageC, String onMessageC, String buttonMessageC, float circleOrbitC){
frameWCS = frameWC;
xSpeedCS = xSpeedC;
ySpeedCS = ySpeedC;
moveLeftCS = moveLeftC;
moveUpCS = moveUpC;
alphaCS = alphaC;
bgColorCS = bgColorC;
outlineCS = outlineC;
outerCircleWeightCS = outerCircleWeightC;
laptopStrokeWeightCS = laptopStrokeWeightC;
startingPointCS = startingPointC;
leftDotRaiseCS = leftDotRaiseC;
leftDownCS = leftDownC;
centerDotRaiseCS = centerDotRaiseC;
centerDownCS = centerDownC;
rightDotRaiseCS = rightDotRaiseC;
rightDownCS = rightDownC;
specialRadiiCS = specialRadiiC;
buttonXCS = buttonXC;
buttonYCS = buttonYC;
buttonStateCS = buttonStateC;
buttonTextSizeCS = buttonTextSizeC;
offMessageCS = offMessageC;
onMessageCS = onMessageC;
buttonMessageCS = buttonMessageC;
circleOrbitCS = circleOrbitC;
}
public void main(String[] args){
}
public void updateAlpha(){
/*
updates alpha versions of color variables that account for the alpha of the color, we have to put this
so that it updates every frame, otherwise the transparency will only update with every bounce. This way
the color updates with each bounce but the transparency constantly updates every frame (or 60 times per second)
*/
baseColorAlpha = color(red(baseColor),green(baseColor),blue(baseColor), alpha);
accentColorAlpha = color(red(accentColor),green(accentColor),blue(accentColor), alpha);
/*
transparency of objects changes with X position of the mouse, 1st quarter of the screen
= 25% brightness, 2nd quarter = 50%, 3rd quarter = 75%, 4th quarter = 100%
*/
if (mouseX < width / 3){
alpha = 75;
} else
if (mouseX > width / 3 && mouseX < 2 * width / 3) {
alpha = 150;
} else
if (mouseX > width * 2 / 3 && mouseX < width){
alpha = 255;
}
}
void resetBackground(){
//reset background to prevent copies of the laptop from generating
background(bgColor);
//set outline color
stroke(outline);
fill(baseColorAlpha);
}
void updateRadii (){
//changing radii of shapes based on button
if (buttonStateCS == true){
specialRadiiCS = 2 * frameW;
} else {
specialRadiiCS = 0;
}
}
void generateComputer(){
//making the frame
rect(frameX, frameY, frameW, frameH);
//making the screen
fill(accentColorAlpha);
rect(frameX, frameY, frameW - frameW / 5, frameH - frameH * 4.0/15.0);
//switching back to the base color for the moving ellipses on the screen
fill(baseColorAlpha);
//creating the laptop keyboard
fill(accentColorAlpha);
beginShape();
vertex(frameX - frameW / 2, frameY + frameH / 2);
vertex(frameX - (frameW / 2 + 15), frameY + frameH / 2 + 15);
vertex(frameX + frameW / 2 + 15, frameY + frameH / 2 + 15);
vertex(frameX + frameW / 2, frameY + frameH / 2);
endShape();
}
void dots(){
rect(frameX - frameW / 5,frameY + leftDotRaise + startingPoint,frameH / 5,frameH / 5,specialRadiiCS);
//moving the dots
if (leftDotRaise >= frameH * (11.0 / 75.0)){
leftDown = false;
} else
if (leftDotRaise <= frameH * (-11.0 / 75.0)){
leftDown = true;
}
if (leftDown == true){
leftDotRaise += frameH / 75;
} else if (leftDown == false){
leftDotRaise -= frameH / 75;
}
rect(frameX,frameY + centerDotRaise, frameH / 5, frameH / 5,specialRadiiCS);
if (centerDotRaise >= frameH * (11.0 / 75.0)){
centerDown = false;
} else
if (centerDotRaise <= frameH * (-11.0 / 75.0)){
centerDown = true;
}
if (centerDown == true){
centerDotRaise += frameH / 75;
} else if (centerDown == false){
centerDotRaise -= frameH / 75;
}
rect(frameX + frameW / 5,frameY + rightDotRaise - startingPoint,frameH / 5,frameH / 5,specialRadiiCS);
if (rightDotRaise >= frameH * (11.0 / 75.0)){
rightDown = false;
} else
if (rightDotRaise <= frameH * (-11.0 / 75.0)){
rightDown = true;
}
if (rightDown == true){
rightDotRaise += frameH / 75;
} else if (rightDown == false){
rightDotRaise -= frameH / 75;
}
startingPoint = 0;
}
void generateOrbitals(){
//creating and animated the outer rotating circles
pushMatrix();
translate(frameX, frameY);
rotate(circleOrbitCS);
translate(frameW * 1.5, frameH / -10);
circleOrbitCS += 0.01;
rect(0, 0, frameW / 2, frameW / 2, specialRadiiCS);
popMatrix();
pushMatrix();
translate(frameX, frameY);
rotate(circleOrbitCS);
translate(frameW * -1.5, frameH / 10);
circleOrbitCS += 0.01;
rect(0, 0, frameW / 2, frameW / 2, specialRadiiCS);
popMatrix();
pushMatrix();
translate(frameX, frameY);
rotate(circleOrbitCS);
translate(frameH / 10, frameW * 1.5);
circleOrbit += 0.01;
rect(0, 0, frameW / 2, frameW / 2, specialRadiiCS);
popMatrix();
pushMatrix();
translate(frameX, frameY);
rotate(circleOrbit);
translate(frameH / -10, frameW * -1.5);
circleOrbit += 0.01;
rect(0, 0, frameW / 2,frameW / 2, specialRadiiCS);
popMatrix();
}
void generateOuterCircle(){
noFill();
stroke(accentColor);
strokeWeight(outerCircleWeight);
rect(frameX, frameY, frameW * 4, frameW * 4,specialRadii);
strokeWeight(laptopStrokeWeight);
}
void bounce(){
if (frameX + 2 * frameW > width) {
moveLeft = true;
baseColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
accentColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
} else if (frameX - 2 * frameW < 0) {
moveLeft = false;
baseColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
accentColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
}
if (frameY + 8.0/3.0 * frameH > height) {
moveUp = true;
baseColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
accentColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
} else if (frameY - 8.0/3.0 * frameH < 0) {
moveUp = false;
baseColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
accentColor = color(random(50, 255), random(50, 255), random(50, 255),alpha);
}
if (moveLeft == true) {
xSpeed = abs(xSpeed) * -1;
} else {
xSpeed = abs(xSpeed);
}
if (moveUp == true) {
ySpeed = abs(ySpeed) * -1;
} else {
ySpeed = abs(ySpeed);
}
}
void updateCoords(){
//update coords
println("Screensaver Icon is currently at (" + frameX + ", " + frameY + ')');
}
void generateSquareButton(){
//square-ification button
fill(accentColor);
rect(buttonXCS,buttonYCS, 200, 200, specialRadiiCS);
fill(255);
textSize(buttonTextSizeCS);
text(buttonMessageCS,buttonXCS,buttonYCS+5);
}
void alignShapes(){
//letting the program know that we are referencing X and Y coords of a rectangle or text box by its center
rectMode(CENTER);
textAlign(CENTER);
}
void testForButton(){
//check if the mouse was pressed at the button's coordinates
if (mouseX > buttonXCS - 100 && mouseY > buttonYCS - 100 && mouseX < buttonXCS + 50 && mouseY < buttonYCS + 50){
//if the button is on, turn it off
if (buttonStateCS == true){
buttonStateCS = false;
buttonMessageCS = offMessageCS;
} else
//if the button is off, turn it on
if (buttonStateCS == false){
buttonStateCS = true;
buttonMessageCS = onMessageCS;
}
}
}
void move(){
frameX += xSpeed;
frameY += ySpeed;
}
void display(){
updateAlpha();
resetBackground();
updateRadii();
generateComputer();
dots();
generateOrbitals();
generateOuterCircle();
bounce();
move();
updateCoords();
generateSquareButton();
}
}
//creating the first instance of the screensaver as an object
screenSavers instance1 = new screenSavers(frameW,xSpeed,ySpeed,moveLeft,moveUp,alpha,bgColor,outline,outerCircleWeight,laptopStrokeWeight,startingPoint,leftDotRaise,leftDown,centerDotRaise, centerDown, rightDotRaise, rightDown, specialRadii, buttonX, buttonY, buttonState, buttonTextSize, offMessage, onMessage, buttonMessage,circleOrbit);
//creating the second instance of the screensaver as an object
screenSavers instance2 = new screenSavers(frameW,xSpeed,ySpeed,moveLeft,moveUp,alpha,bgColor,outline,outerCircleWeight,laptopStrokeWeight,startingPoint,leftDotRaise,leftDown,centerDotRaise, centerDown, rightDotRaise, rightDown, specialRadii, buttonX, buttonY, buttonState, buttonTextSize, offMessage, onMessage, buttonMessage,circleOrbit);
//creating the third instance of the screensaver as an object
screenSavers instance3 = new screenSavers(frameW,xSpeed,ySpeed,moveLeft,moveUp,alpha,bgColor,outline,outerCircleWeight,laptopStrokeWeight,startingPoint,leftDotRaise,leftDown,centerDotRaise, centerDown, rightDotRaise, rightDown, specialRadii, buttonX, buttonY, buttonState, buttonTextSize, offMessage, onMessage, buttonMessage,circleOrbit);
//setup loop, runs ONCE
void setup() {
/*note: to see the console update the X and Y, comment out fullScreen();
and un-comment size(1000,1000); */
//enters fullscreen, regardless of device resolution
fullScreen();
//uncomment this for seeing coords updated
//size(1000,1000);
//makes the framerate go from 24 to a smoother 60 frames. If I don't add this your eyes will hurt
frameRate(60);
instance1.alignShapes();
instance2.alignShapes();
instance3.alignShapes();
}
void draw() {
instance1.display();
instance2.display();
instance3.display();
}
//////////////////////////////////////////////////////////////////
//do something when mouse is pressed
void mousePressed(){
instance1.testForButton();
instance2.testForButton();
instance3.testForButton();
}```
Right now you initialize all 3 instances with the exact same properties. They are only "combined" because you made them the same. You should identify what you want to be different between them, and pass in different properties.
Other notes:
Why does screenSavers have a main() function? Delete it
Please rename it to ScreenSaver.
Do not distinguish using C vs CS. Just name them the same. But use the this keyword to distinguish the class vars. example: this.frameW = frameW;
Use proper indentation with if statements.
Found it a few days later by the way, I was looking for the this keyword

p5.js: Random movement of drawing tool

I coded this drawing tool:
var a = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 255);
}
function draw() {
fill(0, 255, 255, random(255));
translate(mouseX, mouseY);
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Now I would like to have a movement, without doing it with the cursor. I have thought about something like this:
var a;
function centerCanvas() {
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
a.position(x, y);
}
function setup() {
a = createCanvas(windowHeight, windowHeight);
centerCanvas();
}
function draw() {
fill(0, 255, 255, random(255));
var x =
windowHeight / 2 +
sin(frameCount * 0.01) * cos(frameCount * 0.04) * windowHeight / 3;
var y =
windowHeight / 2 +
cos(frameCount * 0.01) * sin(frameCount * 0.04) * windowHeight / 3;
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Unfortunately, it doesn't work. It also would be cool if the movement would be random inside the canvas. Does anyone know how to do it?
This (almost) worked for me:
let wander;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 0);
wander = new Vehicle(0, 0);
}
function draw() {
wander.wander();
wander.update();
wander.edges();
wander.show();
}
class Vehicle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(1, 0);
this.acc = createVector(0, 0);
this.maxSpeed = 4;
this.maxForce = 0.2;
this.r = 16;
this.wanderTheta = PI / 2;
this.xoff = 0;
}
wander() {
let angle = noise(this.xoff) * TWO_PI * 2;
let steer = p5.Vector.fromAngle(angle);
steer.setMag(this.maxForce);
this.applyForce(steer);
this.xoff += 0.01;
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.set(0, 0);
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
textAlign(CENTER, CENTER);
textSize(120);
fill(0, 255, 255, random(255));
text("*", 0, 0);
pop();
}
edges() {
let hitEdge = false;
if (this.pos.x > width + this.r) {
this.pos.x = -this.r;
hitEdge = true;
} else if (this.pos.x < -this.r) {
this.pos.x = width + this.r;
hitEdge = true;
}
if (this.pos.y > height + this.r) {
this.pos.y = -this.r;
hitEdge = true;
} else if (this.pos.y < -this.r) {
this.pos.y = height + this.r;
hitEdge = true;
}
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Using P5.js's noise function is a really accurate way to represent wandering. With a little tinkering you can get the effect you want.
EDIT
This is your (debugged) code:
let a;
let r;
function centerCanvas() {
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
a.position(x, y);
}
function setup() {
a = createCanvas(windowHeight, windowHeight);
centerCanvas();
}
function draw() {
fill(0, 255, 255, random(255));
const x = windowHeight / 2 +
sin(frameCount * 0.01) * cos(frameCount * 0.04) * windowHeight / 3;
const y = windowHeight / 2 +
cos(frameCount * 0.01) * sin(frameCount * 0.04) * windowHeight / 3;
translate(x, y);
rotate(a * 0.08);
textSize(50);
textAlign(CENTER, CENTER);
text('*', 0, 0);
a += 1;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
How about this?
var a = 0;
var x = 0;
var y = 0;
var delta = 1;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 255);
}
function draw() {
fill(0, 255, 255, random(255));
x = x + 2 + Math.random();
y = y + 0.5 + Math.random();
x = x * delta;
y = y * delta;
if (x < 0) delta = -1;
translate((x) % windowWidth,(y) % windowHeight);
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>

p5.js change object colour after X frames

I would like to change the fill colour of an object over time. Is there a way to change the fill colour of an object after X frames?
I am learning about constructors, and I am thinking that in the code's updateParticle function, after this.age counts to 'X', the fill colour of the ellipse could change.
'''
function Particle(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.age = 0;
this.drawParticle = function() {
fill(this.colour);
noStroke();
ellipse(this.x, this.y, this.size);
}
this.updateParticle = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
this.age++;
}
}
function Emitter(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.particles = [];
this.startParticles = [];
this.lifetime = 0;
this.addParticle = function() {
var p = new Particle(random(this.x - 10, this.x + 10),
random(this.y - 10, this.y + 10),
random(this.xSpeed - 0.4, this.xSpeed + 0.4),
random(this.ySpeed - 5, this.ySpeed - 1),
random(this.size - 4, this.size + 40),
this.colour);
return p;
}
this.startEmitter = function(startParticles, lifetime) {
this.startParticles = startParticles;
this.lifetime = lifetime;
for (var i = 0; i < startParticles; i++) {
this.particles.push(this.addParticle());
}
}
this.updateParticles = function() {
var deadParticles = 0
for (var i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].drawParticle();
this.particles[i].updateParticle();
if (this.particles[i].age > random(0, this.lifetime)) {
this.particles.splice(i, 1);
deadParticles++;
}
}
if (deadParticles > 0) {
for (var i = 0; i < deadParticles; i++) {
this.particles.push(this.addParticle());
}
}
}
}
var emit;
function setup() {
createCanvas(800, 600);
emit = new Emitter(width / 2, height - 100, 0, -1, 10, color(200, 0, 200, 50));
emit.startEmitter(600, 4000);
}
function draw() {
background(200);
emit.updateParticles();
}
'''
Well you could just:
if(frameCount % 30 == 0){ // % 30 is the remainder of num / 30, so 4 % 3 = 1, since 3 / 3 = 0 And 4 / 3 = 3.33
fill("lime") // these are just preset colors in p5.js AND css lime == rgb(0,255,0)
} else {
fill('darkred')
}
or you could also do it with for example a switch statement: using background for no reason
switch(MY_frameCount){
case 1:
background('blue')
break
case 2:
background("darkgreen")
break
case 376:
background(crimson)
// break
}
MY_frameCount ++
or:
if(Math.random() < 0.1){
fill(Math.random() * 255, Math.random() * 255, Math.random() * 255)
} // this should on average fill with random color every 10 frames

How To Capture the color from screen in mouse position using Unity and C#?

I did not find a direct function in Color section or since there is no direct C# Unity function for picking the color from post render. How is the best approach for picking the color in the mouse position?
I have done research and looks like there is posible to make a screenshot and then look into the texture calculating the mouse position.
Input.GetMouseButtonDown(0)
Application.CaptureScreenshot("Screenshot.png");
// get the color pixel in the same coordinates of the mouse position
Vector3 mouseCoordinates = Input.mousePosition;
myFinalColor = tex.GetPixel((int)mouseCoordinates.x, (int)mouseCoordinates.y);
Or do I have to make a second camera and attach it to a mesh render?
You just need to use GetPixel(x,y)
This is very simple.
Save Screenshot to Texture2D for example MyTexture
And add .GetPixel( x postion of moue , Y position of mouse )
Save it to your color for GetScreenShot ( make your View to Texture2D )
Color TheColorPicked;
if (Input.GetMouseButtonDown(0))
{
TheColorPicked = MyTexture.GetPixel(Input.mousePosition.x,
Input.mousePosition.y);
}
Yes you can make your own colour picker. Here is the code thanks to Git-hub this page.
using UnityEngine;
using System.Collections;
// relies on: http://forum.unity3d.com/threads/12031-create-random-colors?p=84625&viewfull=1#post84625
public class ColorPicker : MonoBehaviour {
public bool useDefinedPosition = false;
public int positionLeft = 0;
public int positionTop = 0;
// the solid texture which everything is compared against
public Texture2D colorPicker;
// the picker being displayed
private Texture2D displayPicker;
// the color that has been chosen
public Color setColor;
private Color lastSetColor;
public bool useDefinedSize = false;
public int textureWidth = 360;
public int textureHeight = 120;
private float saturationSlider = 0.0F;
private Texture2D saturationTexture;
private Texture2D styleTexture;
public bool showPicker = false;
void Awake() {
if (!useDefinedPosition) {
positionLeft = (Screen.width / 2) - (textureWidth / 2);
positionTop = (Screen.height / 2) - (textureHeight / 2);
}
// if a default color picker texture hasn't been assigned, make one dynamically
if (!colorPicker) {
colorPicker = new Texture2D(textureWidth, textureHeight, TextureFormat.ARGB32, false);
ColorHSV hsvColor;
for (int i = 0; i < textureWidth; i++) {
for (int j = 0; j < textureHeight; j++) {
hsvColor = new ColorHSV((float)i, (1.0f / j) * textureHeight, 1.0f);
colorPicker.SetPixel(i, j, hsvColor.ToColor());
}
}
}
colorPicker.Apply();
displayPicker = colorPicker;
if (!useDefinedSize) {
textureWidth = colorPicker.width;
textureHeight = colorPicker.height;
}
float v = 0.0F;
float diff = 1.0f / textureHeight;
saturationTexture = new Texture2D(20, textureHeight);
for (int i = 0; i < saturationTexture.width; i++) {
for (int j = 0; j < saturationTexture.height; j++) {
saturationTexture.SetPixel(i, j, new Color(v, v, v));
v += diff;
}
v = 0.0F;
}
saturationTexture.Apply();
// small color picker box texture
styleTexture = new Texture2D(1, 1);
styleTexture.SetPixel(0, 0, setColor);
}
void OnGUI(){
if (!showPicker) return;
GUI.Box(new Rect(positionLeft - 3, positionTop - 3, textureWidth + 60, textureHeight + 60), "");
if (GUI.RepeatButton(new Rect(positionLeft, positionTop, textureWidth, textureHeight), displayPicker)) {
int a = (int)Input.mousePosition.x;
int b = Screen.height - (int)Input.mousePosition.y;
setColor = displayPicker.GetPixel(a - positionLeft, -(b - positionTop));
lastSetColor = setColor;
}
saturationSlider = GUI.VerticalSlider(new Rect(positionLeft + textureWidth + 3, positionTop, 10, textureHeight), saturationSlider, 1, -1);
setColor = lastSetColor + new Color(saturationSlider, saturationSlider, saturationSlider);
GUI.Box(new Rect(positionLeft + textureWidth + 20, positionTop, 20, textureHeight), saturationTexture);
if (GUI.Button(new Rect(positionLeft + textureWidth - 60, positionTop + textureHeight + 10, 60, 25), "Apply")) {
setColor = styleTexture.GetPixel(0, 0);
// hide picker
showPicker = false;
}
// color display
GUIStyle style = new GUIStyle();
styleTexture.SetPixel(0, 0, setColor);
styleTexture.Apply();
style.normal.background = styleTexture;
GUI.Box(new Rect(positionLeft + textureWidth + 10, positionTop + textureHeight + 10, 30, 30), new GUIContent(""), style);
}
}
You can also find this helpfull asset store packages 1 2.

Use an object with this code? Processing

How can I use the code I have now with an object where I can store the number of times the ball bounces and the color (when i add random color) and speed. Any pointers or tips would be greatful. I am new to OOP and it can get confusing for me. Thanks in advance
float x;
float y;
float yspeed = 0;
float xspeed = 0;
float balldiameter = 10;
float ballradius = balldiameter/2;
void setup() {
size (400,400);
background (255);
fill (0);
ellipseMode(CENTER);
smooth();
noStroke();
x = random(400);
y = 0;
}
void draw() {
mouseChecks();
boundaryChecks();
ballFunctions();
keyFunctions();
}
void mouseChecks() {
if (mousePressed == true) {
x = mouseX;
y = mouseY;
yspeed = mouseY - pmouseY;
xspeed = mouseX - pmouseX;
}
}
void boundaryChecks() {
if (y >= height - ballradius) {
y = height - ballradius;
yspeed = -yspeed/1.15;
}
if (y <= ballradius) {
y = ballradius;
yspeed = -yspeed/1.35;
}
if (x >= width -ballradius) {
x = width -ballradius;
xspeed = -xspeed/1.10;
}
if (x <= ballradius) {
x = ballradius;
xspeed = -xspeed/1.10;
}
}
void ballFunctions() {
if (balldiameter < 2) {
balldiameter = 2;
}
if (balldiameter > 400) {
balldiameter = 400;
}
ballradius = balldiameter/2;
background(255); //should this be in here?
ellipse (x,y,balldiameter,balldiameter);
yspeed = yspeed += 1.63;
// xspeed = xspeed+=1.63;
y = y + yspeed;
x = x + xspeed;
}
void keyFunctions() {
if (keyPressed) {
if(keyCode == UP) {
balldiameter +=1;
}
if (keyCode == DOWN) {
balldiameter -=1;
}
}
}
you will probably want to do the following:
create a new file called Ball.pde
In that file write:
public class Ball {
public float x;
public float y;
public float yspeed;
public float xspeed;
public float diameter;
public float radius;
public Ball(float initial_x, float initial_y, float diam) {
this.x = initial_x;
this.y = initial_y;
this.xspeed = 0;
this.yspeed = 0;
this.diameter = diam;
this.radius = diam/2;
}
public void move() {
// movement stuff here
}
}
This will give you a very basic Ball class. You can now use this class in your main sketch file like so:
Ball my_ball = new Ball(50, 50, 10);
you can access the balls members using:
my_ball.xspeed;
my_ball.yspeed;
my_ball.anything_you_defined_in_ball;
This will allow you yo store all relevent variables for the ball within its own class. you can even create more than 1.
Ball my_ball1 = new Ball(50, 50, 10);
Ball my_ball2 = new Ball(20, 20, 5);
Just to note that in Proccesing you don't need to create a new file for that, the code can go either in the same file (very bad practice as pointed below) or in a new tab of the IDE. If you are using the Processing IDE you can choose "new tab" from the arrow menu in the right and it will create the file for you. It will have ".pde" extension.

Resources