LibGDX applyLinearImpulse trying to implement Gravity....Confused - java

Street Fighter 2d clone I'm trying to get the player Ken to come back down after jumping. He just goes higher and higher but I want it to be like gravity so he's pulled back down. Then I will set a ground level where he cant pass through.
I've researched the applyLinearImpulse method to be called on the body which is initialised beforre asa I kept getting null pointer exception it seems that now it don't crash but Ken just gets drawn further up the Y Axis. Its left me very confused.
Any advice links greatly appreciated.
Ken class
public class Ken extends Player {
private static final int FRAME_COLS = 6, FRAME_ROWS = 1;
private static final int COLUMNS_KICK = 6;
private static final int COLUMNS_LEFT = 8;
private static final int COLUMNS_RIGHT = 8;
private static final int COLUMNS_JUMP = 10;
private static final int COLUMNS_PUNCH = 6;
private static final int COLUMNS_FRONTFLIP = 8;
private static final int COLUMNS_BACKFLIP = 8;
public static final int FRAME_FRONTFLIP = 1;
public static final int FRAME_BACKLIP = 1;
float x, y;
Animation<TextureRegion> walkAnimation;
Animation<TextureRegion> kickAnimation;
Animation<TextureRegion> punchAnimation;
Animation<TextureRegion> leftAnimation;
Animation<TextureRegion> rightAnimation;
Animation<TextureRegion> jumpAnimation;
Animation<TextureRegion> frontFlipAnimation;
Animation<TextureRegion> backFlipAnimation;
Texture walkSheet;
Texture kickSheet;
Texture punchSheet;
Texture leftSheet;
Texture rightSheet;
Texture jumpSheet;
Texture frontFlipSheet;
Texture backFlipSheet;
public Body body;
public World world;
boolean alive = true;
private final static int STARTING_X = 50;
private final static int STARTING_Y = 30;
TextureRegion reg;
float stateTime;
public Ken(GameScreen screen){
this.world = screen.getWorld();
defineKen();
createIdleAnimation();
kickAnimation();
punchAnimation();
lefttAnimation();
righttAnimation();
jumpAnimation();
frontFlipAnimation();
backFlipAnimation();
this.setPosition(STARTING_X, STARTING_Y);
}
public void createIdleAnimation() {
walkSheet = new Texture(Gdx.files.internal("ken/idle.png"));
TextureRegion[][] tmp = TextureRegion.split(walkSheet,
walkSheet.getWidth() / FRAME_COLS,
walkSheet.getHeight() / FRAME_ROWS);
TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
walkFrames[index++] = tmp[i][j];
}
}
walkAnimation = new Animation<TextureRegion>(0.1f, walkFrames);
stateTime = 0f;
reg=walkAnimation.getKeyFrame(0);
}
public void kickAnimation(){
kickSheet = new Texture(Gdx.files.internal("ken/kick_low.png"));
TextureRegion [][] tmp = TextureRegion.split(kickSheet, kickSheet.getWidth() / COLUMNS_KICK,
kickSheet.getHeight() / FRAME_ROWS);
TextureRegion[] kickFrames = new TextureRegion[COLUMNS_KICK * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
kickFrames[index++] = tmp[i][j];
}
}
kickAnimation = new Animation<TextureRegion>(8f, kickFrames);
stateTime = 6f;
reg = kickAnimation.getKeyFrame(1);
}
public void lefttAnimation(){
leftSheet = new Texture(Gdx.files.internal("ken/parry_b.png"));
TextureRegion [][] tmp = TextureRegion.split(leftSheet, leftSheet.getWidth() / COLUMNS_LEFT,
leftSheet.getHeight() / FRAME_ROWS);
TextureRegion[] leftFrames = new TextureRegion[COLUMNS_LEFT * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_LEFT; j++) {
leftFrames[index++] = tmp[i][j];
}
}
leftAnimation = new Animation<TextureRegion>(0.1f, leftFrames);
stateTime = 0f;
reg = punchAnimation.getKeyFrame(0);
}
public void righttAnimation(){
rightSheet = new Texture(Gdx.files.internal("ken/parry_f.png"));
TextureRegion [][] tmp = TextureRegion.split(rightSheet, rightSheet.getWidth() / COLUMNS_RIGHT,
rightSheet.getHeight() / FRAME_ROWS);
TextureRegion[] rightFrames = new TextureRegion[COLUMNS_RIGHT * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_RIGHT; j++) {
rightFrames[index++] = tmp[i][j];
}
}
rightAnimation = new Animation<TextureRegion>(0.1f, rightFrames);
stateTime = 0f;
reg = rightAnimation.getKeyFrame(0);
}
public void punchAnimation(){
punchSheet = new Texture(Gdx.files.internal("ken/punch.png"));
TextureRegion [][] tmp = TextureRegion.split(punchSheet, punchSheet.getWidth() / COLUMNS_PUNCH,
punchSheet.getHeight() / FRAME_ROWS);
TextureRegion[] punchFrames = new TextureRegion[COLUMNS_PUNCH * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_PUNCH; j++) {
punchFrames[index++] = tmp[i][j];
}
}
punchAnimation = new Animation<TextureRegion>(0.1f, punchFrames);
stateTime = 0f;
reg = punchAnimation.getKeyFrame(0);
}
public void jumpAnimation(){
jumpSheet = new Texture(Gdx.files.internal("ken/jump.png"));
TextureRegion [][] tmp = TextureRegion.split(jumpSheet, jumpSheet.getWidth() / COLUMNS_JUMP,
jumpSheet.getHeight() / FRAME_ROWS);
TextureRegion[] jumpFrames = new TextureRegion[COLUMNS_JUMP * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < COLUMNS_JUMP; j++) {
jumpFrames[index++] = tmp[i][j];
}
}
jumpAnimation = new Animation<TextureRegion>(0.1f, jumpFrames);
stateTime = 0f;
reg = jumpAnimation.getKeyFrame(0);
}
public void frontFlipAnimation(){
frontFlipSheet = new Texture(Gdx.files.internal("ken/front_flip.png"));
TextureRegion [][] tmp = TextureRegion.split(frontFlipSheet, frontFlipSheet.getWidth() / COLUMNS_FRONTFLIP,
frontFlipSheet.getHeight() / FRAME_ROWS);
TextureRegion[] frontFlipFrames = new TextureRegion[COLUMNS_FRONTFLIP * FRAME_FRONTFLIP];
int index = 0;
for (int i = 0; i < FRAME_FRONTFLIP; i++) {
for (int j = 0; j < COLUMNS_FRONTFLIP; j++) {
frontFlipFrames[index++] = tmp[i][j];
}
}
frontFlipAnimation = new Animation<TextureRegion>(0.1f, frontFlipFrames);
stateTime = 0f;
reg = frontFlipAnimation.getKeyFrame(0);
}
public void backFlipAnimation(){
backFlipSheet = new Texture(Gdx.files.internal("ken/back_flip.png"));
TextureRegion [][] tmp = TextureRegion.split(backFlipSheet, backFlipSheet.getWidth() / COLUMNS_BACKFLIP,
backFlipSheet.getHeight() / FRAME_BACKLIP);
TextureRegion[] backFlipFrames = new TextureRegion[COLUMNS_BACKFLIP * FRAME_BACKLIP];
int index = 0;
for (int i = 0; i < FRAME_BACKLIP; i++) {
for (int j = 0; j < COLUMNS_BACKFLIP; j++) {
backFlipFrames[index++] = tmp[i][j];
}
}
backFlipAnimation = new Animation<TextureRegion>(0.1f, backFlipFrames);
stateTime = 0f;
reg = backFlipAnimation.getKeyFrame(0);
}
#Override
public void act(float delta) {
super.act(delta);
stateTime += delta;
stateTime += delta;
reg = walkAnimation.getKeyFrame(stateTime,true);
if(Gdx.input.isKeyPressed(Input.Keys.A)){
reg = kickAnimation.getKeyFrame(stateTime, false);
this.addAction(Actions.moveTo(getX() +2, getY(), 1 / 10F));
}
if(Gdx.input.isKeyPressed(Input.Keys.S)){
reg = punchAnimation.getKeyFrame(stateTime, false);
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
reg = leftAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 10, getY(), 1 / 10f ));
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
reg = rightAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 10, getY(), 1 /10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.UP)){
body.applyLinearImpulse(new Vector2(0, 20), body.getWorldCenter(), true);
reg = jumpAnimation.getKeyFrame(stateTime, false);
this.addAction(Actions.moveTo(getX(), getY() + 10, 1/ 10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.D)){
reg = frontFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() + 5, getY(), 1 / 10f));
}
if(Gdx.input.isKeyPressed(Input.Keys.W)){
reg = backFlipAnimation.getKeyFrame(stateTime, true);
this.addAction(Actions.moveTo(getX() - 5, getY(), 1 / 10F));
}
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
batch.draw(reg,getX(),getY(),getWidth()/2,getHeight()/2,getWidth(),getHeight(),getScaleX(),getScaleY(),getRotation());
}
private void defineKen(){
BodyDef bdef = new BodyDef();
bdef.position.set(32 / 100, 32 / 100);
bdef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(7 / 100);
fdef.shape = shape;
body.createFixture(fdef).setUserData(this);
body.createFixture(fdef).setUserData(this);
}
}
Repo
Thanks alot

You work with Box2d and Box2d is a 2d physics engine so it also integrated gravity.
First, when you create your World you can define the gravity force:
world = new World(new Vector2(0,-15f), true);
This will pull your Player down.
Then you must update the world every frame. So call in the render() method:
world.step(delta, 6, 2);
Now the Body position will be calculated by the world and gravity apply to the body.
Important now is that you first have a Static body as Ground otherwise, the body will fall down infinitely. Secondly, you must change the place where you draw the Image of Ken to the place of the Body so in act() method update the position:
setX(body.getPosition().x);
setY(body.getPosition().y);
Maybe you look for some Box2d tutorials to have a better understanding:
https://www.gamedevelopment.blog/full-libgdx-game-tutorial-box2d/

Related

Create a java class for generating a cylinder

I am supposed to create a new class SCylinder extended from SObject, which builds a cylinder model. It is expected that the class SCylinder works like the class SSphere provided for rendering the sphere, except that SCylinder is used for rendering a cylinder.
I know I have to change the genData() so that I can create a cylinder but have no idea where to start. Any advice and tips would be much appreciated.
package Objects;
public class SCylinder extends SObject{
private float radius;
private float height;
private int slices;
private int stacks;
public SCylinder(){
super();
init();
update();
}
public SCylinder(float radius){
super();
init();
this.radius = radius;
update();
}
public SCylinder(float radius, float height,int slices, int stacks){
super();
this.radius = radius;
this.height=height;
this.slices = slices;
this.stacks = stacks;
update();
}
private void init(){
this.radius = 1;
this.slices = 20;
this.stacks = 20;
}
#Override
protected void genData() {
int i,j,k;
double deltaLong=PI*2/slices;
double deltaLat= PI/stacks;
// Generate vertices coordinates, normal values, and texture coordinates
numVertices = (slices+1)*(stacks-1)+2;
vertices = new float[numVertices*3];
normals = new float[numVertices*3];
textures = new float[numVertices*2];
//North pole point
normals[0] = 0; normals[1] = 0; normals[2] = 1;
vertices[0] = 0; vertices[1] = 0; vertices[2] = radius;
textures[0]= 0.5f; textures[1] = 1.0f;
k = 1;
//vertices on the main body
for(i=1;i<stacks;i++){
for(j=0;j<=slices;j++){
normals[3*k] = sin(deltaLat*i)*cos(deltaLong*j);
normals[3*k+1] = sin(deltaLat*i)*sin(deltaLong*j);
normals[3*k+2] = cos(deltaLat*i);
vertices[3*k] = radius*normals[3*k];
vertices[3*k+1] = radius*normals[3*k+1];
vertices[3*k+2] = radius*normals[3*k+2];
textures[2*k] = (float) j/slices;
textures[2*k+1] = 1-(float) i/stacks;
k++;
}
}
//South pole point
normals[3*k] = 0; normals[3*k+1] = 0; normals[3*k+2] = -1;
vertices[3*k] = 0; vertices[3*k+1] = 0; vertices[3*k+2] = -radius;
textures[2*k] = 0.5f; textures[2*k+1] = 0.0f; k++;
// Generate indices for triangular mesh
numIndices = (stacks-1)*slices*6;
indices = new int[numIndices];
k = 0;
//North Pole, numElement:slices*3
for(j=1;j<=slices;j++){
indices[k++] = 0;
indices[k++] = j;
indices[k++] = j+1;
}
//South Pole, numElement:slices*3
int temp = numVertices-1;
for(j=temp-1;j>temp-slices-1;j--){
indices[k++] = temp;
indices[k++] = j;
indices[k++] = j-1;
}
//Main body, numElement:(stacks-2)*slices*6
for(i=1;i<stacks-1;i++){
for(j=1;j<=slices;j++){
//each quad gives two triangles
//triangle one
indices[k++] = (i-1)*(slices+1)+j;
indices[k++] = i*(slices+1)+j;
indices[k++] = i*(slices+1)+j+1;
//triangle two
indices[k++] = (i-1)*(slices+1)+j;
indices[k++] = i*(slices+1)+j+1;
indices[k++] = (i-1)*(slices+1)+j+1;
}
}
}
public void setRadius(float radius){
this.radius = radius;
updated = false;
}
public void setSlices(int slices){
this.slices = slices;
updated = false;
}
public void setStacks(int stacks){
this.stacks = stacks;
updated = false;
}
public float getRadius(){
return radius;
}
public int getSlices(){
return slices;
}
public int getStacks(){
return stacks;
}
}

How can I set the value of c when generating a Mandelbrot fractal?

The equation for generating a Mandelbrot fractal is Zn+1 = Zn^2+C. The issue is that, in a computer program, C is used for zoom/resolution and location on screen. My question is, how can I make it so that I can get a fractal like this:
Wolfram
(equation f(z) = sin(z/c), z0 = c )
My code (from Rosetta Code):
public class MandelbrotSet extends JFrame {
private static final long serialVersionUID = 5513426498262284949L;
private final int MAX_ITER = 570;
private final double ZOOM = 150;
private BufferedImage image;
private double zx, zy, cX, cY, tmp;
public MandelbrotSet() {
super("Mandelbrot Set");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < getHeight(); y++) {
for (int x = 0; x < getWidth(); x++) {
zx = zy = 0;
cX = (x - 400) / ZOOM;
cY = (y - 300) / ZOOM;
int iter = MAX_ITER;
while (zx * zx + zy * zy < 4 && iter > 0) {
tmp = zx * zx - zy * zy + cX;
zy = 2.0 * zx * zy + cY;
zx = tmp;
iter--;
}
image.setRGB(x, y, iter | (iter << 8));
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
new MandelbrotSet().setVisible(true);;
}
}
By trigonometric theorems
sin(A+i*B)=sin(A)*cos(i*B)+ cos(A)*sin(i*B)
=sin(A)*cosh(B )+i*cos(A)*sinh(B )
and for the quotient using z=x+i*y and c=a+i*b
(x+i*y)/(a+i*b)=(x+i*y)*(a-i*b)/(a*a+b*b)
so that for the sine expression above
A = (a*x+b*y)/(a*a+b*b)
B = (a*y-b*x)/(a*a+b*b)
In javascript a small script to generate this fractal can look like this:
function cosh(x) { return 0.5*(Math.exp(x)+Math.exp(-x)); }
function sinh(x) { return 0.5*(Math.exp(x)-Math.exp(-x)); }
function rgb(r,g,b) { return "rgb("+r+","+g+","+b+")"; }
var colors = new Array(24);
for(var k=0; k<8; k++) {
colors[ k] = rgb(k*64,(7-k)*64,(7-k)*64);
colors[ 8+k] = rgb((7-k)*64,k*64,(7-k)*64);
colors[16+k] = rgb((7-k)*64,(7-k)*64,k*64);
}
var cvs = document.getElementById('sine-fractal');
var ctx = cvs.getContext('2d');
var cx = 0.0, cy = 0.0;
var dx = 1.0;
var tiles = 100;
var scale = Math.min(cvs.width, cvs.height) / tiles;
ctx.scale(scale, scale);
function localx(i) { return cx-dx + 2*i*dx/tiles; }
function localy(j) { return cy-dx + 2*j*dx/tiles; }
for (var i = 0; i < tiles; i++) {
var a = localx(i);
for (var j = 0; j < tiles; j++) {
var b = localy(j);
var r2 = a*a + b*b;
var x = a, y = b;
var rounds = 0;
var max = 500;
while (x * x + y * y < 4 && rounds < max) {
var u = (a*x + b*y) / r2, v = (a*y - b*x) / r2;
x = Math.sin(u) * cosh(v);
y = Math.cos(u) * sinh(v);
rounds++;
}
ctx.fillStyle = colors[rounds % 24];
ctx.fillRect(i, j, 1, 1);
}
}
<canvas id='sine-fractal' width=200 height=200></canvas>

Getting a specific row in a spritesheet libgdx java

I am trying to access a specific row in my sprite sheet and I am thoroughly confused as to how to do this. I tried modifying a tutorial I found to accomplish this but when I run the code the length of my animation array is of size 0 when there are five rows in my spritesheet and 12 columns. My class should always fill my animation array with one row of information. Here is my Animator class
public Animator(Texture spriteSheet, int cols){
this.walkSheet = spriteSheet;
this.cols = cols;
this.rows = 1;
}
public void create() {
TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth()/cols, walkSheet.getHeight()/rows); // #10
walkFrames = new TextureRegion[cols];
anim = new Animation[rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
walkFrames[j] = tmp[i][j];
}
anim[i] = new Animation(0.025f, walkFrames);
}
stateTime = 0f; // #13
}
public void render(int index, SpriteBatch spriteBatch, int x, int y, int width, int height) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
currentFrame = anim[index].getKeyFrame(stateTime, true);
spriteBatch.draw(currentFrame, x, y, width, height);
}
Any help with this will be extremely appreciated as I have spent so much time trying to figure this out.
I haven't tried this code yet, but I think this could work for what you want.
public Animator(Texture spriteSheet, int cols, int rows){
this.walkSheet = spriteSheet;
this.cols = cols;
this.rows = rows;
}
public void create() {
TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth()/cols, walkSheet.getHeight()/rows); // #10
anim = new Animation[rows];
for (int i = 0; i < rows; i++) {
walkFrames = new TextureRegion[cols];
for (int j = 0; j < cols; j++) {
walkFrames[j] = tmp[i][j];
}
anim[i] = new Animation(0.025f, walkFrames);
}
stateTime = 0f; // #13
}
public void render(int index, SpriteBatch spriteBatch, int x, int y, int width, int height) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
currentFrame = anim[index].getKeyFrame(stateTime, true);
spriteBatch.draw(currentFrame, x, y, width, height);
}

Neural net learning algorithm

I have been working on making a neural network that has a goal, of hitting a moving target, it has inputs based on the distance from the shooter to the target from both axis, the rotation of the shooter, and the wind speed.
Every 5 seconds the shooter resets to a different position on the screen.
I have attempted to use a back prop algorithm, by giving calculating the error based on the distance the bullet hits from the target, and if the shooter doesn't fire a shot in the 5 second window there is also an error propagated.
My network however does not seem to be learning properly, I was wondering if anyone could point me in the right direction.
Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import java.util.stream.DoubleStream;
import javax.swing.JFrame;
public class ClassMain extends JFrame{
int ShooterLocationX = 100;
int ShooterLocationY = 150;
int shooterDiameter = 35;
int targetX = 525;
int targetY = 100;
int targetWidth = 15;
int targetLength = 50;
double error;
double targetVectorX=ShooterLocationX + 100;
double targetVectorY = ShooterLocationY+shooterDiameter/2;
boolean direction = false;
boolean ShotFired = false;
boolean rotateDirection;
boolean start =true;
boolean shotbeenFires;
double ShooterRotation = 0;
double[] outputs1 = new double[4];
double[] outputs2 = new double[8];
double[] outputs3 = new double[8];
double[] outputs4 = new double[3];
Percepton[] input = new Percepton[4];
Percepton[] hidden = new Percepton[8];
Percepton[] hidden2 = new Percepton[8];
Percepton[] output = new Percepton[3];
Shooter shot = new Shooter(ShooterRotation);
Random random = new Random();
long StartTime = 0;
long CurrTime = 0;
public static void main(String []args){
ClassMain CM= new ClassMain();
CM.setup();
}
public void setup(){
setSize(900,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
createBufferStrategy(2);
repaint();
for(int i = 0; i < 4; i ++){
input[i] = new Percepton();
input[i].setInputNumber(1);
}
for(int i =0;i < 8;i++){
hidden[i] = new Percepton();
hidden[i].setInputNumber(input.length);
}
for(int i =0;i < 8;i++){
hidden2[i] = new Percepton();
hidden2[i].setInputNumber(input.length);
}
for(int i = 0;i < 3; i++){
output[i] = new Percepton();
output[i].setInputNumber(hidden.length);
}
}
public void run(){
double[] temp = new double[10];
if(start){
StartTime = System.currentTimeMillis();
start = false;
}
CurrTime = System.currentTimeMillis();
if(CurrTime-StartTime > 5000){
ShooterLocationX=random.nextInt(400);
ShooterLocationY=random.nextInt(275);
shot.newX = ShooterLocationX+(shooterDiameter/2)-5;
shot.newY = ShooterLocationY+(shooterDiameter/2)-5;
shot.windSpeed = (float)(random.nextInt(200)-100)/100;
start = true;
if(!shotbeenFires){
error+=15;
}
for(int n = 0; n < output.length;n++){
output[n].learn(n, error, output[n].weights[n]);
}
for(int n = 0; n < hidden2.length;n++){
hidden2[n].learn(n, error, hidden2[n].weights[n]);
}
for(int n = 0; n < hidden.length;n++){
hidden[n].learn(n, error, hidden[n].weights[n]);
}
for(int n = 0; n < input.length;n++){
input[n].learn(n, error, input[n].weights[n]);
}
error = 0;
shotbeenFires = false;
}
outputs1[0] = input[0].sigmoid((((Math.max(ShooterLocationX,targetX)-Math.min(ShooterLocationX,targetX))/300)*2)*input[0].weights[0],1*input[0].biasWeight);
outputs1[1] = input[1].sigmoid((((Math.max(ShooterLocationY,targetY)-Math.min(ShooterLocationY,targetY))/150)*2)*input[1].weights[0],1*input[1].biasWeight);
outputs1[2] = input[2].sigmoid((ShooterRotation)*input[2].weights[0],1*input[2].biasWeight);
outputs1[3] = input[3].sigmoid((shot.windSpeed)*input[3].weights[0],1*input[3].biasWeight);
System.out.println("\n");
for(int n = 0;n < hidden.length;n++){
for(int i = 0;i<temp.length;i++){
temp[i] = 0;
}
for(int i = 0;i < outputs1.length;i++){
temp[i] = outputs1[i]*hidden[n].weights[i];
}
outputs2[n] = (float)DoubleStream.of(temp).sum();
outputs2[n] = hidden[1].sigmoid(outputs2[n],1*hidden[n].biasWeight);
//System.out.print(outputs2[n]);
}
System.out.println("\n");
for(int n = 0;n < hidden2.length;n++){
for(int i = 0;i<temp.length;i++){
temp[i] = 0;
}
for(int i = 0;i < outputs2.length;i++){
temp[i] = outputs2[i]*hidden2[n].weights[i];
}
outputs3[n] = (float)DoubleStream.of(temp).sum();
outputs3[n] = hidden2[1].sigmoid(outputs3[n],1*hidden2[n].biasWeight);
//System.out.print(outputs3[n]);
}
System.out.println("\n");
for(int n = 0;n < output.length;n++){
for(int i = 0;i<temp.length;i++){
temp[i] = 0;
}
for(int i = 0;i < outputs1.length;i++){
temp[i] = outputs3[n]*hidden[n].weights[i];
}
outputs4[n] = (float)DoubleStream.of(temp).sum();
outputs4[n] = output[n].sigmoid(outputs4[n],1*output[n].biasWeight);
//System.out.print(outputs4[n]);
}
if(!ShotFired){
System.out.println("\n");
if(outputs4[0] > 0.5){
ShotFired = true;
shot.rotation = ShooterRotation;
}
if (outputs4[1] > 0.5){
ShooterRotation = ShooterRotation + outputs3[1];
}
if(outputs4[2] > 0.5){
ShooterRotation =ShooterRotation - outputs3[2];
}
if(ShooterRotation*360 > 360){
ShooterRotation = ((ShooterRotation * 360) + 360) /360;
}else if(ShooterRotation * 360 < 0){
ShooterRotation = ((ShooterRotation*360)-360) /360;
}
}
for(int i = 0; i < 1; i++){
if(ShotFired){
shotbeenFires = true;
shot.newLocationX(shot.newX);
shot.newLocationY(shot.newY);
}
if(targetY < 20 ||targetY+targetLength >300){
direction = !direction;
}
if(direction){
targetY += 8;
}else{
targetY -= 8;
}
if(shot.newX + (15)>= targetX && shot.newX + 15 < targetX +targetWidth && shot.newY + 15> targetY && shot.newY <targetY + targetLength){
System.out.println("Target Hit");
error -= 10;
shot.newX = ShooterLocationX + shooterDiameter/2-5;
shot.newY = ShooterLocationY + shooterDiameter/2-5;
ShotFired = false;
}else if(shot.newX > 600|| shot.newX<10||shot.newY<10||shot.newY> 290){
System.out.println("MISS");
error += (shot.newY - targetY);
shot.newX = ShooterLocationX + shooterDiameter/2-5;
shot.newY = ShooterLocationY + shooterDiameter/2-5;
ShotFired = false;
}
}
repaint();
}
public void paint(Graphics g){
targetVectorX = ShooterLocationX + shooterDiameter/2 + Math.cos(Math.toRadians(ShooterRotation)) * 100;
targetVectorY = ShooterLocationY + shooterDiameter/2 + Math.sin(Math.toRadians(ShooterRotation)) * 100;
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.fillOval(ShooterLocationX, ShooterLocationY, shooterDiameter, shooterDiameter);
g2.setPaint(Color.RED);
g2.drawLine(ShooterLocationX + shooterDiameter/2, ShooterLocationY+shooterDiameter/2, (int)targetVectorX, (int)targetVectorY);
g2.setPaint(Color.BLUE);
g2.fillRect(targetX, targetY, targetWidth, targetLength);
g2.setPaint(Color.RED);
g2.fillOval((int)shot.newX, (int)shot.newY, 10, 10);
g2.setPaint(Color.gray);
g2.fillRect(600, 0, 300,300);
for(int i = 0; i < input.length;i++){
if(outputs1[i] > 0.5){
g2.setPaint(Color.red);
}else{
g2.setPaint(Color.white);
}
g2.drawOval(625+i*35, 250, 25, 25);
for(int j = 0;j<hidden.length;j++){
g2.drawLine(640+i*35, 250, 615+j*30, 195);
}
}
for(int i = 0; i < hidden.length;i++){
if(outputs2[i] > 0.5){
g2.setPaint(Color.red);
}else{
g2.setPaint(Color.white);
}
g2.drawOval(605+i*30, 175, 20, 20);
for(int j = 0;j<hidden2.length;j++){
g2.drawLine(615+i*30, 175, 615+j*30, 145);
}
}
for(int i = 0; i < hidden2.length;i++){
if(outputs3[i] > 0.5){
g2.setPaint(Color.red);
}else{
g2.setPaint(Color.white);
}
g2.drawOval(605+i*30, 125, 20, 20);
for(int j = 0;j<output.length;j++){
g2.drawLine(615+i*30, 125, 697+j*50, 75);
}
}
for(int i = 0; i < output.length;i++){
if(outputs4[i] > 0.5){
g2.setPaint(Color.red);
}else{
g2.setPaint(Color.white);
}
g2.drawOval(685+i*50, 50, 25, 25);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
run();
}
}
public class Shooter {
double windSpeed = 0.5;
int distance = 0;
double newX;
double newY;
double rotation;
double temp = 0;
public Shooter(double rotate){
rotation = rotate*360;
windSpeed = windSpeed*5;
}
public void newLocationX(double XPrev){
newX = XPrev + Math.cos(Math.toRadians(rotation)) * 20;
}
public void newLocationY(double YPrev){
newY = YPrev + Math.sin(Math.toRadians(rotation)) * 20;
newY =newY - windSpeed;
}
}
import java.util.Random;
public class Percepton {
int numOfInputs = 100;
float[] weights = new float[numOfInputs];
int sum;
double learningRate = 0.1;
float biasWeight;
float a;
float out;
Random random = new Random();
public void setWeight(int index,float weight){
weights[index] = weight;
}
public void setInputNumber(int inputs){
numOfInputs = inputs;
for(int i = 0; i < inputs; i++){
weights[i] = (float)(random.nextInt(400)-200)/200;
biasWeight = (float)(random.nextInt(400)-200)/200;
//System.out.println(weights[i]);
}
}
public void learn(int index, double error, float value){
weights[index] += (float)learningRate * (float)error * value;
}
public double sigmoid(double input,double bias){
return (float) (1/(1+Math.exp(-input*bias)));
}
}

Painting balloons on Graphics2D

I want to make bubble shooter game and I have problem with generate bubbles at start. When trying to compile program, I have error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
public class MyPanel extends JPanel {
Init init;
public MyPanel(){
super();
init = new Init();
}
public void paint(Graphics g){
Dimension size = getSize();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GRAY);
g2d.fillRect(0, 0, size.width, size.height - 70);
for(int j = 0; j < 10; j++)
for(int i = 0; i < 20; i++){
init.fields[i][j].b.paint(g); //here compiler shows error
}
}
}
public class Field {
private int x;
private int y;
private int r = 30;
public Baloon b;
public Field(int x, int y){
this.x = x*r;
this.y = y*r;
}
public void addBaloon(int n){
b = new Baloon(this.x, this.y, r, n);
}
}
public class Init {
Parser pr = new Parser();
private int r = pr.getRadius();
private int x = pr.getXDimension();
private int y = pr.getYDimension();
private int ni = pr.getColorRange();
Field[][] fields = new Field[x][y];
private int startX = 20;
private int startY = 10;
public Init(){
for(int yi = 1; yi<y; yi++){
for (int xi = 1; xi<x; xi++){
fields[xi][yi] = new Field(xi*r, yi*r);
}
}
for(int yi = 1; yi < startY; yi ++){
for(int xi = 1 ; xi < startX; xi++){
Random rand = new Random();
int n = rand.nextInt(ni);
fields[xi][yi].addBaloon(n);
}
}
}
}
You are initializing array from index 1:
for(int yi = 1; yi<y; yi++){
for (int xi = 1; xi<x; xi++){
fields[xi][yi] = new Field(xi*r, yi*r);
}
}
While accessing it from 0 like:
for(int j = 0; j < 10; j++)
for(int i = 0; i < 20; i++){
init.fields[i][j].b.paint(g); //here compiler shows error
}
Array index starts from 0 and goes upto n-1. So you need to initialize like:
for(int yi = 0; yi<y; yi++){
for (int xi = 0; xi<x; xi++){
fields[xi][yi] = new Field(xi*r, yi*r);
}
}

Categories