how to pass value to paint method - graphics

I am just at very beginnig in Java coding, so far I could solve my problems finding solutions on internet, but this time I just stucked.
I want to create a grid(pattern) of filled rectangles, and it works fine, but then I would like to change colour of rectangles on specific position, and this part is just not working. I have no idea why, what am I doing wrong ?
// **file : MainWindow.java **
import java.util.Scanner;
import javax.swing.JFrame;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class MainWindow {
JFrame frame = new JFrame();
int pos_X;
int pos_Y;
// constructor for frame
public MainWindow (String title) {
frame.setSize(1000, 1000);
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i=0;i<26;i++){ // works fine
for (int j=0;j<26;j++){
Shape shape = new Shape (110+i*20,110+j*20,19,19,5,100,220); //(x,y, width,height, R-colour, G-colour, B-colour)
frame.add(shape);
frame.setVisible(true); }}
pos_X= 15;
pos_Y = 15;
Shape shape = new Shape (110+pos_X*20,110+pos_Y*20,19,19,250,0,20); // it doesn't work ???
frame.add(shape);
frame.setVisible(true);
}
public static void main(String[] args){
new MainWindow(" my window ");
}
}
// **file : Shape.java **
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Color.*;
import javax.swing.JComponent;
public class Shape extends JComponent{
int width, height, xcoord, ycoord, col_r, col_g,col_b;
//constructor
public Shape (int x, int y ,int w,int h, int k, int l, int m)
{
this.width = w;
this.height = h;
this.xcoord = x;
this.ycoord = y;
this.col_r = k;
this.col_g = l;
this.col_b = m;
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
Color x= new Color( col_r,col_g, col_b );
g.setColor(x);
g.fillRect(xcoord, ycoord, width, height);
}
}

If I understand right, what you want could be done ensuring the shape has drawn after the grid, so
pos_X= 15;
pos_Y = 15;
Shape shape = new Shape (110+pos_X*20,110+pos_Y*20,19,19,250,0,20); // it doesn't work ???
frame.setComponentZOrder(shape,0)
frame.add(shape);
frame.setVisible(true);
...
please note the
frame.setComponentZOrder(shape,0)
which ensure that the colored shape is drawn above the others.
In alternative your
P.S.
if it doesn't work try frame.setComponentZOrder(shape,frame.getComponentCount())
See also here for an alternative

Related

Unity 5 collision still occuring

I'm working on a 2D plane dodging game and I'm having issues in Unity 5, I'm trying to stop the collision between two incoming planes, I've tried many different solutions but those don't work. I can't put them in different layers because they still need to collide with the player. This is the code I have for the first plane. Enemy and Bullets are both tags. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletPlane : MonoBehaviour {
public float speed = 6f;
public float reloadTime = 1f;
public GameObject bulletPrefab;
public GameObject explosion;
public GameObject smoke;
public GameObject warning;
public GameObject self;
public float reloadSecond = .10f;
private float elapsedTime = 0;
public float timeElapsed = 0;
private Rigidbody2D rigidBody;
void Start()
{
rigidBody = GetComponent<Rigidbody2D> ();
rigidBody.velocity = new Vector2 (0, speed);
Vector3 warningPos = transform.position;
warningPos += new Vector3 (0, -10.5f, 0);
Instantiate (warning, warningPos, Quaternion.identity);
}
void Update() {
elapsedTime++;
Vector3 spawnPos = transform.position;
Vector3 secondPos = transform.position;
elapsedTime = 0f;
spawnPos += new Vector3 (0, -1.2f, 0);
secondPos += new Vector3 (-1, -0.9f, 0);
Instantiate (bulletPrefab, spawnPos, Quaternion.identity);
Instantiate (smoke, secondPos, Quaternion.identity);
if (elapsedTime > reloadSecond) {
spawnPos += new Vector3 (0, -1.2f, 0);
secondPos += new Vector3 (-1, -0.9f, 0);
Instantiate (bulletPrefab, spawnPos, Quaternion.identity);
Instantiate (smoke, secondPos, Quaternion.identity);
elapsedTime = 0f;
timeElapsed++;
}
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.CompareTag ("Player")) {
Destroy (other.gameObject);
} else if (other.gameObject.CompareTag ("Enemy")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
} else if (other.gameObject.CompareTag ("Bullets")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
}
}
}
This is the code for the other enemy plane
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPlane : MonoBehaviour {
public float speed = -6f;
public float reloadTime = 1f;
public GameObject bulletPrefab;
public GameObject explosion;
private float elapsedTime = 0;
private Rigidbody2D rigidBody;
void Start()
{
rigidBody = GetComponent<Rigidbody2D> ();
rigidBody.velocity = new Vector2 (0, speed);
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.CompareTag ("Ally")) {
} else if (other.gameObject.CompareTag ("Enemy")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
} else if (other.gameObject.CompareTag ("BulletPlane")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
}
}
}
You still be able to set the layer, while your player can still be able to interact with.
Suppose you have 3 different objects
Plane A
Plane B
Player
and you want Plane A to don't collide with Plane B, but still collide with Player.
You can set the collision matrix on
Edit -> Project Settings -> Physics2D
How to setup?
Set Plane A to Layer 'CollideOnlyWithPlayer'
Set Player to layer 'Player'
Then in the collision matrix, you can unchek all for layer CollideOnlyWithPlayer
But check for CollideWithPlayer to Player layer
The collision matrix define how object interact within the other object in layer.
It's defined by two indices, the vertical one and the horizontal one.
When you check for example, Vertical 'Player' to Horizontal 'Player'
this means, that your player can interact with player
And when you check for example, Vertical 'Player' to Horizontal 'CollideWithPlayer'
this means that your player physic can interact with object layered to CollideWithPlayer.
Pleas see the full documentation here
https://docs.unity3d.com/Manual/LayerBasedCollision.html

Exporting video from processing 3

I am using processing-3.2.2 for audio visualization. I have the code to play the visualiser but I don't know how to save it as a video(.mp4) file.
Here's what I wrote:
import ddf.minim.*;
import ddf.minim.analysis.*;
Minim minim;
AudioPlayer player;
AudioMetaData meta;
BeatDetect beat;
int r = 200;
float rad = 70;
void setup()
{
size(500, 500);
//size(600, 400);
minim = new Minim(this);
player = minim.loadFile("son_final.mp3");
meta = player.getMetaData();
beat = new BeatDetect();
player.play();
//player.play();
background(-1);
noCursor();
}
void draw()
{
float t = map(mouseX, 0, width, 0, 1);
beat.detect(player.mix);
fill(#1A1F18,50);
noStroke();
rect(0, 0, width, height);
translate(width/2, height/2);
noFill();
fill(-2, 10);
if (beat.isOnset()) rad = rad*0.9;
else rad = 70;
ellipse(0, 0, 2*rad, 2*rad);
stroke(-1, 50);
int bsize = player.bufferSize();
for (int i = 0; i < bsize - 1; i+=5)
{
float x = (r)*cos(i*2*PI/bsize);
float y = (r)*sin(i*2*PI/bsize);
float x2 = (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
float y2 = (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
line(x, y, x2, y2);
}
beginShape();
noFill();
stroke(-1, 50);
for (int i = 0; i < bsize; i+=30)
{
float x2 = (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
float y2 = (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
vertex(x2, y2);
pushStyle();
stroke(-5);
strokeWeight(2);
point(x2, y2);
popStyle();
}
endShape();
if (flag) showMeta();
}
void showMeta() {
int time = meta.length();
textSize(50);
textAlign(CENTER);
text( (int)(time/1000-millis()/1000)/60 + ":"+ (time/1000-millis()/1000)%60, -7, 21);
}
boolean flag =false;
void mousePressed() {
if (dist(mouseX, mouseY, width/2, height/2)<150) flag =!flag;
}
void keyPressed() {
if(key=='e')exit();
}
I know I can import MovieMaker library but I don't know how to use it in this code. Please suggest some changes.
Thank you.
You can use the Video Export library for that. More info here: http://funprogramming.org/VideoExport-for-Processing/
Then all you'd do is create an instance of VideoExport and then call videoExport.saveFrame() at the end of your draw() function.
import com.hamoid.*;
VideoExport videoExport;
void setup() {
size(600, 600);
videoExport = new VideoExport(this, "basic.mp4");
}
void draw() {
background(#224488);
rect(frameCount * frameCount % width, 0, 40, height);
videoExport.saveFrame();
}
There are a ton of resources online. I recommend googling "Processing video export" for a ton of results. Then try something out and post an MCVE (not your entire project) showing exactly where you're stuck.

TextureRegion cuts texture in a wrong way

I want to have a background texture with 3 rectangles and i want to create animation with them, - texture
But first rectangle cuts in a proper way and two others are cut in a dumb way
Proper way,
Dumb way #1,
Dumb way #2
Here is my code.
public class MainMenu implements Screen{
Texture background_main;
TextureRegion[] background_textures;
Animation background_animation;
SpriteBatch batch;
TextureRegion current_frame;
float stateTime;
BobDestroyer game;
OrthographicCamera camera;
public MainMenu(BobDestroyer game){
this.game = game;
}
#Override
public void show() {
camera = new OrthographicCamera();
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
background_main = new Texture(Gdx.files.internal("main_menu_screen/Background.png"));
background_textures = new TextureRegion[3];
for(int i = 0; i<3; i++){
background_textures[i] = new TextureRegion(background_main,0, 0+72*i, 128, 72+72*i);
}
background_animation = new Animation(2f,background_textures);
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
current_frame = background_animation.getKeyFrame(stateTime, true);
batch.begin();
batch.draw(current_frame,0, 0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
batch.end();
}
}
If I understand you correctly, are you trying to create 3 TextureRegions of the same width/height? If yes, your issue may be with:
new TextureRegion(background_main,0, 0+72*i, 128, 72+72*i)
I think you'd want:
new TextureRegion(background_main,0, 0+72*i, 128, 72)
As the 128x72 is the width/height (not x/y positions) of your next TextureRegions, and do you not want them all the same height (72) as opposed to varying heights (72+72*i)?

JavaFX 2.2 MouseEvent in SubScene does not work properly

I am trying to get this to work for sometime and I cannot figure out what wrong with my code. This leads me to believe there is some issues in SubScene Mouse listener. Any idea is appreciated.
Basically I have a scene contains two subscenes, one for the toolbar and one for the floor which has bunch of lines making it looks like tiles. I added mouse listeners so that when I clicked on the floor and move the mouse, the camera will move as if I am walking on the floor.
The problem is that the floor only recognize mouse event when I clicked on the intersection between the first vertical and the first horizontal line (yup, took me a while to figure that out). Mouse event should occur everywhere on entire floor.
Here is the code.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.SubScene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class FloorTest extends Application {
double mousex, mousey;
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
Group bargroup = new Group();
SubScene bar = new SubScene(bargroup, 300, 20, true, SceneAntialiasing.DISABLED);
bargroup.getChildren().add(btn);
Group floorgroup = new Group();
SubScene floor = new SubScene(floorgroup, 300, 250, true, SceneAntialiasing.DISABLED);
ObservableList<Node> list = floorgroup.getChildren();
for(int i = 0; i < (300/20); i++)
{
double x = i * 20;
Line line = new Line(x, 0, x, 250);
list.add(line);
}
for(int i = 0; i < (250/20); i++)
{
double y = i * 20;
Line line = new Line(0, y, 300, y);
list.add(line);
}
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setNearClip(0.1);
camera.setFarClip(10000.0);
camera.setTranslateZ(-200);
floor.setCamera(camera);
floor.setOnMousePressed((MouseEvent event) -> {
mousex = event.getSceneX();
mousey = event.getSceneY();
});
floor.setOnMouseDragged((MouseEvent event) -> {
double x = event.getSceneX();
double y = event.getSceneY();
camera.relocate(camera.getLayoutX() + (x - mousex), camera.getLayoutY() + (y - mousey));
});
Group mainroot = new Group();
mainroot.getChildren().addAll(floor, bar);
Scene scene = new Scene(mainroot, 300, 250, true);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
It seems that setting the subscene.setPickOnBounds(true) should help in proper recognition of the mouse events for the whole subscene. Tested with javafx 8.
Please try using scene instead of floor variable in event handlers
Example:
scene.setOnMousePressed((MouseEvent event) -> {
mousex = event.getSceneX();
mousey = event.getSceneY();
});
scene.setOnMouseDragged((MouseEvent event) -> {
double x = event.getSceneX();
double y = event.getSceneY();
camera.relocate(camera.getLayoutX() + (x - mousex), camera.getLayoutY() + (y - mousey));
});
That helps me

Rotate a group of Graphics objects around a single point?

I found an image online (http://i.stack.imgur.com/y1oT4.png) and I'm trying to take the sun and sky and make them rotate around the center of the screen, such that the sun and its rays appear to be spinning.
I intend to use a timer to control the movement, but I can't figure out how to rotate by an arbitrary angle. In other words, I know how to rotate by increments of 90 (switch the width and height), but what I'm trying to do is group a set of objects and rotate them around a single point.
I've looked around and found the AffineTransform() method, but I can't figure out if this is really what I need or how to use it if it is.
EDIT: Does this solve my problem? How to rotate Graphics in Java I will try it and update.
EDIT: It got me closer, but did not fix it. It returns this runtime error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at FallScene.rotateBack(FallScene.java:77)
at SceneDriver$1TimerListener.actionPerformed(SceneDriver.java:66)
at javax.swing.Timer.fireActionPerformed(Timer.java:312)
at javax.swing.Timer$DoPostEvent.run(Timer.java:244)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
main.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Press any key to continue...
The call at FallScene.rotateBack(FallScene.java:77) is:
bg.rotate(Math.toRadians(deg));
...which goes to:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Get the size of the component window
int w = getWidth();
int h = getHeight();
// The Graphics2D object for the BACKGROUND
Graphics2D bg = (Graphics2D)g;
// Sun
Color solarYellow = new Color(255, 218, 0);
bg.setPaint(solarYellow);
Ellipse2D.Double sun = new Ellipse2D.Double((w / 2) - 150, (h / 2) - 150, 300, 300);
bg.fill(sun); bg.draw(sun);
}
If you still need it, I think this operational and commented code should help you understand how to draw it.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.util.TimerTask;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SunRotate extends JComponent
{
public static void main(String[] args) {
final SunRotate sunRotate = new SunRotate(45);
JFrame f = new JFrame();
f.setContentPane(sunRotate);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(new Dimension(800, 600));
f.setVisible(true);
new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sunRotate.deltaAngle(.3f);
sunRotate.repaint();
}
}, 16, 16); // every 16 milliseconds
}
private float angle;
public void deltaAngle(float delta) {
angle += delta;
}
public SunRotate(float angle) {
this.angle = angle;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Move and rotate
g2.translate(w/2.0, h/2.0);
g2.rotate(Math.toRadians(angle));
// draw around 0,0
Color solarYellow = new Color(255, 218, 0);
g2.setPaint(solarYellow);
Ellipse2D.Double sun = new Ellipse2D.Double( -150, -150, 300, 300);
g2.fill(sun);
{ // draw some rays because the sun is round so we don't see the rotation
// make a ray (triangle)
Path2D ray = new Path2D.Float();
ray.moveTo(0, 0);
ray.lineTo(1000, 50);
ray.lineTo(1000, -50);
ray.closePath();
// draw N rays, rotating each time
int N = 20;
for (int i = 0; i < N; i++) {
g2.fill(ray);
g2.rotate(Math.PI * 2 / N);
}
}
}
}

Resources