I need to get the horizontal and vertical movements of a vehicle using the speed, time and angle input. In my target class I have:
public double toRadians = Math.toRadians(angle);
public double getHorizontal() {
return (speed*time*Math.cos(toRadians));
}
public double getVertical() {
return (speed*time*Math.cos(toRadians));
}
however, the values of horizontal and vertical movement give me just the speed*time, so I assume there must be something wrong in the way I declared the math function?
There is something not right about your code.
Hint: what is the difference between these two functions apart from their respective names?
public double getHorizontal() {
return (speed*time*Math.cos(toRadians));
}
public double getVertical() {
return (speed*time*Math.cos(toRadians));
}
Hint 2: Suppose you plot a graph with f(t) on the X axis against f(t) on the Y access, and vary the values of t. what will that graph look like?
I assume there must be something wrong in the way I declared the math function?
The declarations are not the problem. It is the function bodies that the problem.
(Though actually, it is a bit of the problem that, speed, time and radians (or angle) are instance variables rather than arguments to the functions / methods. But deal with that problem after the problem with .... the formulae.)
Related
I am learning Classes and Objects, and I am on reference variables, and accessing an object's data and methods. In my textbook, we created a program which calculates the area of a circle, given the radius.
They declare the object reference variable, create an object, and assign the reference to a variable here:
Circle myCircle = new Circle();
They later give an example below of finding the area (getArea()* just returns the area given the radius):
System.out.println("Area is " + new Circle(5).getArea());
Is the 5 (number in parentheses) an input for the radius?
If so, why isn't it in the getArea() parentheses?
Also, there are no arguments for Circle() so how can you have a number in the () anyway?
*Code for getArea():
By the way, could you get rid of the parentheses if there is only one statement inside?
double getArea()
{
return radius * radius * Math.PI;
}
Please excuse the horrid formatting - I wasn't able to use Ctrl-K, could someone edit it for me please.
Is the 5 (number in parentheses) an input for the radius?
System.out.println("Area is " + new Circle(5).getArea());
Not exactly.
It is the argument passed to a Circle constructor that should very probably value a radius field.
If so, why isn't it in the getArea() parentheses?
getArea() is an instance method of Circle. It relies on the state of the Circle instance that has already a radius information.
So passing a radius argument to getArea() makes no sense.
It would make sense if you had a utility static method in the Circle class to compute a area according to a radius.
For example :
public static double computeArea(double circleRadius){
...
}
You could invoke it in this way :
double area = Cicle.getArea(5.5);
Also, there are no arguments for Circle() so how can you have a number
in the () anyway?
Without a Circle constructor that accepts a radius information, the invocation new Circle(5) cannot compile. So it of course requires one.
You should have a Circle constructor defined such as :
public class Circle{
...
private double radius;
public Circle(double radius){
this.radius = radius;
}
}
by the way, could you get rid of the parentheses if there is only one
statement inside?
Parenthesis () refers to a specification of the Java language to declare method and constructor.
When you declare a method, you need it in any case.
I will try to explain in deep:
public class Circle {
// this variable can access only inside class
private final double radius;
// constructor for class Circle
public Circle(double rad) {
radius = rad;
}
// method of class Circle - can be access outside
public double area() {
return radius*radius*Math.PI;
}
}
when you instantiate class Circle as Circle circle5 = new Circle(5); you got instance of class Circle with encapsulated parameter radius = 5 now, you don't know any details, and just call method double area = circle5.area() to get the area of circle (rad*rad*Pi).
This is dramatically decrease complexity. Even in this very simple example.
now you can print you result
System.out.println(area);
I think, you got the idea.
1st step: you instantiated class and encapsulated all details into it via constructor;
2nd step: you can use you class (methods of the class) and never aware about implementation detail.
And in you sample, calling constructor without parameters new Circle() instead new Circle(5) - this is typographic mistake.
First let me explain constructors in Java.
There are two types of constructors in java: 1. Explicit and 2. Implicit.
Explicit means a constructor with argument and developed by developer.
Implicit means, default or non parameter constructor.
In your case let me analyse the operation:
System.out.println("Area is " + new Circle(5).getArea());
new Circle(5), actually means that invoking a n explicit constructor with input parameter 5.
According to your shared knowledge, it can be understood that a radius is set in this explicit constructor.
I mean, the following constructor should be exist:
public Circle(int i) {
radius = i;
}
Apologies if the title is not appropriate, was having trouble what to call this.
Scenario:
I have a universe type project in java where there are different types of things you can find in a universe (stars, planets, comets etc).
This is part of my university coursework and I'm stuck on one part
I have a class called Space_Object which is a superclass and all things found in the universe inherit it. The superclass has variables such as xPosition, yPosition.
I am currently stuck on trying to get planets to orbit around stars. I am trying to get the x,y coordinates of a star so that the planet can orbit around it (there can be multiple planets and stars). Right now I am passing the star that the planet will orbit around as a field whenever making a new planet.
I created getters inside of Planet to retrieve the x,y of the Star (which works). I am stuck on how can I use that x and y to alter the starting point of the planet. This is what I added to Universe class:
public void setCoordsOfPlanet(Planet planetObj)
{
planetObj.xPosition = planetObj.getSolarSystemX();
}
Which gave me an error of:
xPosition has private access in Space_Object
I am not allowed to make any of the fields public.
Planet class:
public class Planet extends Space_Object
{
private int distanceFromStar;
private int orbitSpeed;
static Star solarSystem;
public Planet(int disFromStar, int orbSpeed, Star solSystem, int objectDiameter, Color objectColor, Universe theUniverse)
{
super(0, 0, 0, 0, objectDiameter, objectColor, theUniverse);
distanceFromStar = disFromStar;
orbitSpeed = orbSpeed;
solarSystem = solSystem;
}
public int getSolarSystemX ()
{
return solarSystem.getXPosition();
}
public int getSolarSystemY ()
{
return solarSystem.getYPosition();
}
}
Just in case, the Space_Object constructor:
public Space_Object(int xPos, int yPos, int xVel, int yVel, int objectDiameter, Color objectColor, Universe theUniverse)
{
xPosition = xPos;
yPosition = yPos;
xSpeed = xVel;
ySpeed = yVel;
color = objectColor;
diameter = objectDiameter;
universe = theUniverse;
universeHeight = universe.getUniverseHeight();
universeWidth = universe.getUniverseWidth();
lifeTime = 1000000;
}
Am I approaching this from the completely wrong angle? I been trying to change things regarding this matter for past three hours and made no progress - any help is appreciated. If you need more code let me know.
PS: All items in the universe are objects and are represented as colour circles on a canvas.
If you are asking how do I modify private fields from another class: then all you need to do is to add setter methods in your Space_Object or Planet class, for example:
public class Planet {
...
public setCoor(int x, int y) {
this.xPosition = x;
this.yPosition = y;
}
}
Now you can call this method from the Star class: planet.setCoor(x, y)
If you want this method to only be accessible from classes of the same package only, remove public.
There are multiple issues here.
Programming stuff
Model of planetary rotation
Use of 'Solar System' when it should be 'Star System' :-) The Solar System is our star system; that's because our star is "Sol"
A1. You need xposition to have a method to set it.
A2a. There are no x and y for our solar system or even a star system. If you're going to model spinning galaxies and/or expanding universe (in which case the galaxies also move in 3d space away from each other,) then the star positions (or positions of any object for that matter) are not fixed.
A2b. If you're going with immobile stars and galaxies, a star (not its system) will have an x and a y.
A2c. A planet revolves around its star in a Kepler orbit with eccentricity greater than 0 and less than 1. To calculate the path, you need axis information for the orbit in addition to the star's location. Wikipedia will have the equations.
A2d. There is no starting position of a planet unless you plan to have planets with unstable orbits. (Or comets which will have their orbits modified during every revolution by the planets they pass by). Planets with stable orbits have always followed and will forever follow the same path (not really, but...) You can place the planet at any point on the orbit and give it appropriate initial velocity (=speed+direction) and watch it go. A3. Self-explanatory
Sounds like a fun project, especially you're animating the model onscreen. In such a case, you also need to decide on your system's clock-speed; the numbers of days that will pass in real time for each second of your simulation time. Additionally, you'll need to select your refresh frequency; how often will you update the screen.
I'm learning a lot more about Java 8 and its functional capabilities, and I wanted to do some more practice with it. Say, for example, I have the following imperative code which is for wrapping a circle around the bounds of the screen:
if (circle.getPosition().getX() > width + circle.getRadius()){
circle.getPosition().setX(-circle.getRadius());
}else if (circle.getPosition().getX() < -circle.getRadius()){
circle.getPosition().setX(width + circle.getRadius());
}
if (circle.getPosition().getY() > height + circle.getRadius()){
circle.getPosition().setY(-circle.getRadius());
}else if (circle.getPosition().getY() < -circle.getRadius()){
circle.getPosition().setY(height + circle.getRadius());
}
How could I go about trying to "Functionalize" it? Maybe some pseudo-code? It seems to me that mutability and state seem inherent in this example.
Is functional programming not a good fit for game development? I love the both, so I'm trying to combine them.
There is nothing inherent about the requirement for mutability in this example. The imperative approach is to modify an existing circles by applying side-effects which alter the state of an existing circle.
The functional approach is to have an immutable data structure and create a function that takes data from the first structure and creates a new structure. In your example, a functional approach would have the circle being immutable, i.e. no setX() or setY() methods.
private Circle wrapCircleAroundBounds(Circle circle, double width, double height) {
double newx = (circle.getPosition().getX() > width + circle.getRadius()) ? -circle.getRadius() : width + circle.getRadius()
double newy = (circle.getPosition().getY() > height + circle.getRadius()) ? -circle.getRadius() : height + circle.getRadius()
return new Circle(newx, newy)
}
Using Java8's functional features, you could then imagine mapping a list of circles to wrapped circles:
circles.stream().map(circ -> wrapCircleAroundBounds(circ, width, height))
The imperative and functional approaches have different advantages, the functional approach, for example, is intrisicaly threadsafe because of the immutability so you should be able to more readily parallelise this kind of code. For instance, one could equally safely write:
circles.parallelStream().map(circ -> wrapCircleAroundBounds(circ, width, height))
I don't think that functional programming is necessarily badly suited to game development but, although it has be done, it's certainly not a standard approach so you won't get the same level of library support if you're using a functional language.
As dfeuer states in his answer, Java's functional features are pretty primitive - you don't have support for algebraic data types, pattern matching, etc which will make it much easier to express problems in a functional style (at least once you get used to those idioms). I agree that at least reading a bit about Haskell, which has an excellent tutorial: http://learnyouahaskell.com/chapters would be a good way to get started. Unlike Scala, which is very much a multiparadigm language, you won't have OOP features to fall back on while you're learning the new style.
For your first point: You "functionalize" your example by thinking about what the code ought to achieve. And this is, you have a circle, and want to compute another circle based on some conditions. But for some reason your imperative upbringing makes you assume that the input circle and the output circle should be stored in the same memory locations!
For being functional, the first thing is to forget memory locations and embrace values. Think of every type the same way you think of int or java.lang.Integer or the other numeric types.
For an example, assume some newbie shows you some code like this:
double x = 3.765;
sin(x);
System.out.println("The square root of x is " + x);
and complains that sin doesn't seem to work. What would you think then?
Now consider this:
Circle myCircle = ....;
wrapAroundBoundsOfScreen(myCircle);
System.out.println("The wrapped-around circle is now " + myCircle);
You will have climbed the first step to functional programming when the latter code seems as absurd to you as the former. And yes, this does mean not to use certain features of the imperative language you are using, or use them extremely sparingly.
Here not much 'functionalization' applicable. But at least we can fight with mutability.
First of all pure functions. This will help to separate logic. Make it clear and easy to test.
Answer the question: what is your code do? It accepts some params and returns two params new x and y.
Next samples will be written with pseudo scala.
So you need a function that will be invoked two times for both x and y calculation.
def (xOrY: Int, widthOrHeight: Int, radius: Int): Int = {
if (x > widthOrHeight + radius) -1*radius else widthOrHeight + radius
// do your calculation here - return x or y values.
}
P.S> so far no matter where you want to apply functional style: as you need to do some business logic it's good to go with functional approach.
But do not try overcomplicate it as it does not help.
So what I would not do for this sample is next (pseudo scala goes next):
def tryToMakeMove(conditions: => Boolean, move: => Unit) = if (conditions) move()
/// DO NOT DO IT AT HOME :)
tryToMakeMove(circle.getPosition().getX() > width + circle.getRadius(), circle.getPosition().setX(-circle.getRadius())).andThen()
tryToMakeMove(circle.getPosition().getX() < -circle.getRadius()), circle.getPosition().setX(width + circle.getRadius()))
).andThen ... so on.
That how functional programs can looks like. I've created the higher-order function (that accepts other functions as an arguments and invoke it inside).
With this functions, i've invoked one be one operations you have to do...
But such functional style does not really help. At all. You should apply it properly only in a places where it's simplify the code.
You can write functional code in just about any programming language, but you can't easily learn functional programming in any language. Java in particular makes functional programming sufficiently painful that people who wanted to do functional programming in the JVM came up with Clojure and Scalaz. If you want to learn the functional way of thinking (what problems it deals with naturally and how, what problems are more awkward and how it manages them, etc.), I strongly recommend that you spend some time with a functional or mostly-functional language. Based on a combination of language quality, ease of sticking to functional idioms, learning resources, and community, my top pick would be Haskell and my next would be Racket. Others will of course have other opinions.
How could I go about trying to "Functionalize" it? Maybe some
pseudo-code? It seems to me that mutability and state seem inherent in
this example.
You could try to limit the mutability to a few functions, and also use final variables inside the functions (which forces you to use expressions rather than statements). Here's one possible way:
Position wrapCircle(Circle circle, int width, int height) {
final int radius = circle.getRadius();
final Position pos = circle.getPosition();
final int oldX = pos.getX();
final int x = (oldX > width + radius) ? -radius : (
(oldX < -radius) ? (width + radius) : oldX);
final int y = // similar
return new Position(x, y);
}
circle.setPosition(wrapCircle(circle, width, height));
Aside, I would make wrapCircle a method of the Circle class, to get:
circle.wrapCircle(width, height);
Or I could go one step further and define a getWrappedCircle method, that returns me a new circle instance:
Circle getWrappedCircle(width, height) {
newCircle = this.clone();
newCircle.wrapCircle(width, height);
return newCircle();
}
.. depending on how you intend to structure the rest of the code.
Tip: Use final keyword as often as you can in Java. It automatically lends to a more functional style.
Is functional programming not a good fit for game development? I love the both, so I'm trying to combine them.
Pure functional programming is slower, because it requires lots of copying / cloning of data. If performance is important, then you could definitely try a mixed approach, as shown above.
I would suggest using as much immutability as possible, followed by benchmarking, and then converting to mutability in only the performance critical sections.
Functional programming fits game development (why would not it?). The question is usually more about performance and memory consumption or even if any functional game engine can beat an existing non-functional one in those metrics. You are not the only person who loves functional programming and game development. Seems like John Carmack does too, watch his keynotes about the topics at Quakecon 2013 starting from 02:05. His notes here and here even give insight on how a functional game engine can be structured.
Setting theoretical foundation aside, there are usually two concepts perceived inherent in functional programming by a newcomer and from a practical prospect. They are data immutability and state absence. The former means that data never changes and the latter means every task is performed as if for the first time with no prior knowledge.
Considering that, you imperative code has two problems: the setters mutate the circle position and the code relies on outside values (a global state) of width and height. To fix them make your function return a new circle on each update and take the screen resolutions as arguments. Let's apply the first clue from the video and pass a reference to the static snapshot of the world and a reference to an entity being "updated" (it is simply this here) to an update function:
class Circle extends ImmutableEntity {
private int radius;
public Circle(State state, Position position, int radius) {
super(state, position);
this.radius = radius;
}
public int getRadius() {
return radius;
}
#Override
public ImmutableEntity update(World world) {
int updatedX = getPosition().getX();
if (getPosition().getX() > world.getWidth() + radius){
updatedX = -radius;
} else if (getPosition().getX() < -radius){
updatedX = world.getWidth() + radius;
}
int updatedY = getPosition().getX();
if (getPosition().getY() > world.getHeight() + radius){
updatedY = -radius;
} else if (getPosition().getY() < -radius) {
updatedY = world.getHeight() + radius;
}
return new Circle(getState(), new Position(updatedX, updatedY), radius);
}
}
class Position {
private int x;
private int y;
//here can be other quantities like speed, velocity etc.
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
class State { /*...*/ }
abstract class ImmutableEntity {
private State state;
private Position position;
public ImmutableEntity(State state, Position position) {
this.state = state;
this.position = position;
}
public State getState() {
return state;
}
public Position getPosition() {
return position;
}
public abstract ImmutableEntity update(World world);
}
class World {
private int width;
private int height;
public World(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
Now the tricky part is how to affect the state of the world and other entities. You can follow the second clue from the video and use event passing mechanism to pass such changes to and fro so the rest of the game knows about all the effects.
Obviously, you can keep only events and rely completely on them even when changing your circle positions. So, if you introduce sort of an id to your entities you will be able to pass MoveEntity(id, newPosition).
OK, it's time for us all to get over how new and shiny Java 8's functional features look. "Functionalizing" something is really not a valid goal to have.
However, the original code here has a good ol' object-oriented problem:
When you say circle.getPosition().setX(...), you are messing with the internal state of the circle (its position) without involving the object itself. That breaks encapsulation. If the circle class were properly designed, then the getPosition() method would return a copy of the position or an immutable position so that you couldn't do this.
That is the problem you really need to fix with this code...
How, then, should you do that?
Well, you could certainly come up with some functional interface in Circle, but honestly your code will be more readable if you just have circle.move(double x, double y);
I have a method that fills an array and I need to find a way to make it repeat a number of times. The purpose is to iterate and reiterate the density of a planet to narrow its mass,gravity and densities at specific points which are concentric shells. This is my first program but, I have learned a decent amount while working on this I think. Thanks everyone
Here is my code sample of the density calculation. I probably included too much but oh well. So I need to make this iterate selected number of times. Each iteration needs to be put back into the mass calculation which will then be put back into the gravity calculation. And then the show starts again.
public class ItrDensityGrid {
public double itrrho[];
double b = InitialConditions.bmod;
// Iterating grid of densities
public ItrDensityGrid(int shells, double radius, double mass){
GravityGrid gg = new GravityGrid(shells, radius, mass);
for(int k = shells; k >= 0; k--){
itrrho[k] = (itrrho[k]*(1+(gg.alpha[k]*(1.0 / 2)))*(1 / (1-((gg.alpha[k])*(1.0 / 2)))));
}
}
}
This can be achieved with the help of Recursion, or looping.
In recursion, you call the method again from inside of the method itself. Make sure to call (or return) conditionally, otherwise, it may lead to infinite loop!
Here is an example with recursion:
public planetMars (double density, double mass) {
// do your calculations
density = density / 10.05312;
mass = mass / 7.2378;
myArray[] = density; // or whatever you want
// if calculations have not narrowed enough, call recursively
if ( density > 5.2)
planetMars (density, mass);
}
alternatively, with loop, you may do something like:
public planetMars (double density, double mass) {
// loop unless the calculation is not cool
while ( density > 5.2) {
// do your calculations
density = density / 10.05312;
mass = mass / 7.2378;
myArray[] = density; // or whatever you want
}
}
you could make a function which checks if the tolerances of your calculations are already good enough, here is some "pseudocode"
while(toleranceIsGood(planet) == false)
{
planet = calculatePlanet(planet);
}
planet would be the array. of course you can implement things like Endless loop detection etc
I reading about Mathematics in Games and am wondering what is the best way to represent a Vector location in Java.
I know there is a Vector class but I don't think this is what I need.
There is also a Matrix class which looks like it may be what I want (a 1 dimensional matrix maybe).
In particular, if I were to create a location Vector such as:
v(x,y,z) where x,y and z are the coordinates in 3D space, what would be the best way to represent this in Java. It would be nice if I could also add, subtract and find the dot-product of Vectors.
ideas?
maybe you could create a 3DVector class
example:
class 3DVector {
int x , y, z;
public 3DVector(int x, int y, int z){
//constructor
}
public 3DVector add(3DVector anotherVector){
}
public 3DVector subtract()....
public 3DVector doProduct().....
}
There is a library for this, See :
javax.vecmath.Vector3d
There is a math library out there but a simple class with 3 floating point numbers is what everyone else uses