Collision if statement doesnt seem to work - java

Basically, Im just trying out a very simple collision test for another program Im working on, but it does seem to so simple (Or maybe Im just an idiot!) Anyway, here is the code:
public void run() {
while(true){
try {
if(rect.rect.intersects(rect1.rect)){
System.out.println("Test1");
if(rect1.x == ((rect.x + rect.width)-1)){
System.out.println("Test2");
rect1.x = rect.x + rect.width;
rect1.dx = 0;
}
}
rect.update();
rect1.update();
Thread.sleep(50);
The program does not get to test2!
Any help to solve this issue is greatly appreciated! Thanks in advance!
Paint component part:
public void paintComponent(Graphics g){
rect1.paint(g);
rect2.paint(g);
g.drawString(String.valueOf(rect1.x), 100, 100);
g.drawString(String.valueOf(rect2.x+rect2.width), 100, 150);
repaint();
}
Image:

Run the program in Eclipse (or your preferred IDE) and use its runtime debug facilities to set a breakpoint at the first if statement. Then step through and examine the values of the variables. Hopefully this will make clear why your code is failing to do what you expect.

How about constructing this method just for debugging convenience (unless you have a debugger):
public static printRectProperties(Rectangle rect, String rectangleName){
System.out.println(rectangleName + ": x = " + rect.x + ", y = "
+ rect.y + ", width = " rect.width + ", height = " + rect.height;
}
Then you can simply call this method to log statistics about the rectangles prior to the execution of the if statement:
if(rect.rect.intersects(rect1.rect)){
System.out.println("Test1");
printRectProperties(rect, "rect");
printRectProperties(rect1, "rect1");
if(rect1.x == ((rect.x + rect.width)-1)){
System.out.println("Test2");
That should make it easy to figure out why "Test2" is never printed.

Related

Bukkit; How to trigger multiple ClickEvent RUN_COMMAND actions with a single click on a single chat message

I've written a rather simple method for my paper/spigot Minecraft server plugin that detects potential lag machines under construction.
The issue I have is that I want to send a single chat message that, when clicked once, will first run a /vanish command on behalf of the clicker.
Then if (and only if) the vanish was successful, I want to run a teleport command to a location included along with the specific instance of the ClickEvent.
Both of those commands need to be completed from the single user click event.
For reference here is the method that calls notifyOps() and includes the TextComponent in question, msg
if (LagMats.contains(blockType) || mat.contains("MINECART") || mat.contains("DOOR")) {
int counter = 0;
for (Material thisMat: LagMats) {
if (thisMat != Material.GRAVEL) {
counter += Utilities.blockCounter(block.getChunk(), thisMat);
}
}
TextComponent warn = new TextComponent("WARN "); warn.setBold(true);
warn.setColor(ChatColor.RED);
TextComponent msg = new TextComponent("Potential lag-machine at " +
block.getX() + ", " + block.getY() + ", " + block.getZ() + " in " + dimension +
" by " + placer_name + " with UUID: " + placer.getUniqueId());
String cmd = "/execute in " + env + " run tp #s " +
block.getX() + " " + block.getY() + " " + block.getZ();
msg.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd));
if (counter > 256) {
Utilities.notifyOps(new TextComponent(warn, msg));
}
}
Oh and the actual little code of notifyOps where the TextComponent is used in a message:
// send a message to all online ops and console
public static boolean notifyOps(TextComponent msg) {
if (msg == null) return false;
for (Player thisPlayer: Bukkit.getOnlinePlayers()) {
try {
if (thisPlayer.isOp()) thisPlayer.spigot().sendMessage(msg);
} catch (Exception e) {return false;}
}
System.out.println(msg.getText());
return true;
}
So I want to have the user click just once, run two commands, the second only if the first succeeds, and would be best if it could be done within the try block the message is sent from.
I could write a custom command for this purpose, and then just run that command, but I rather avoid adding classes for such a small addition if it's actually possible and I just have no idea.
Thanks for any advice or help!
There is no way of doing that without writing a custom command...
This is impossible because the ClickEvent and HoverEvent are entirely client-side. That means that there are no packets sent from the Player to the server. Therefore, it is impossible to callback the click of the Player and call a method to perform what you are trying to do.
You may notice that all the ClickEvent.Actions do not affect the server. OPEN_URL, OPEN_FILE, RUN_COMMAND, SUGGEST_COMMAND, CHANGE_PAGE and COPY_TO_CLIPBOARD are all actions taken on the client-side.
The only way here is to make the client send a command to the server which will trigger a method.

Avoid tooltip grabbing mouse focus

How can I spawn a tooltip close to my cursor without the OnMouseExit handler being called. Is there any way to make the tooltip opaque to mouse focus?
A JIRA issue was created several years ago describing a similar situation: https://bugs.openjdk.java.net/browse/JDK-8118199 .
Working with a canvas I attached mouse listener to continuously show a tooltip and update accordingly to the data drawn beneath it.
Tooltip tt = new Tooltip();
tt.setAnchorLocation(AnchorLocation.CONTENT_BOTTOM_RIGHT);
tt.setAutoFix(false);
double offset = 100;
this.setOnMouseMoved((event) -> {
//Position tooltip
if (!tt.isShowing()) {
tt.show(this, event.getScreenX() - offset, event.getScreenY() - offset);
} else {
tt.setX(event.getScreenX() - offset);
tt.setY(event.getScreenY() - offset);
}
//Update text
int xBucket = (int) ((event.getX() - marginLeft - gridXOffset) / (gridWidth / xSections));
int yBucket = (int) ((event.getY() - marginTop) / (gridHeight / ySections));
DoubleSummaryStatistics stat = dat[xBucket][yBucket];
tt.setText("Occurances: " + stat.getCount() + "\n"
+ "Average Fitness: " + df.format(stat.getAverage()) + "\n"
+ "Max Fitness: " + df.format(stat.getMax()) + "\n"
+ "Min Fitness: " + df.format(stat.getMin()));
});
this.setOnMouseExited((event) -> {
if (tt.isShowing()) {
tt.hide();
}
});
As you can see the tooltip is displayed a little bit to the top left due to the defined offset. If the value is set two a smaller value (20-0) the tooltip will grab the focus as soon as it is displayed and the setOnMouseExit handler will be immediately called resulting in a flickering loop.

bukkit - Waiting?

Recently I started developing a Bukkit Plugin and I need help with sleeping/waiting in my code. I'm kinda new to java so if you could explain it, I would appreciate. Here is my code:
#EventHandler
public void onTnt(PlayerInteractEntityEvent e) {
Player clicker = e.getPlayer();
Player rightclick = (Player) e.getRightClicked();
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
/* Then wait 3 sec. I've tried Thread.Sleep, wait() and sleep(), no sucess*/
if (!(rightclick.isSneaking())) {
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye.");
rightclick.setHealth(0);
}
}
While normally you'd use Thread.sleep for something like this, that would freeze the entire server, and events wouldn't be processed in that time (so even if the player stopped sneaking on their side, they'd still be sneaking from what the server sees).
What you need to do is use a BukkitRunnable (or alternatively a regular Runnable and getServer().getScheduler().scheduleSyncDelayedTask):
#EventHandler
public void onTnt(PlayerInteractEntityEvent e) {
Player clicker = e.getPlayer();
// Needs to be final to reference it later
final Player rightclick = (Player) e.getRightClicked();
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
BukkitRunnable task = new BukkitRunnable() {
#Override
public void run() {
if (!(rightclick.isSneaking())) {
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye.");
rightclick.setHealth(0);
}
}
};
// Run the task on this plugin in 3 seconds (60 ticks)
task.runTaskLater(this, 20 * 3);
}
I am aware of the fact that this is an old question, yet I'd like to add something so that users who will be looking for a way to do may find this.
The simplest say to do this is creating a scheduled task:
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
// The stuff which should be accomplished after the timer runs out goes here.
// Example:
player.sendMessage("The time has ran out!");
}, time);
Now, let's get through the process of understanding what's going on here. Basically, se have created a delayed task (there are two types of scheduled tasks: delayed and repeating tasks).
The first argument of the method above is this. This is supposed to be an instance of your main class (a subclass of org.bukkit.plugin.java.JavaPlugin). This means that if the scheduled task is not in your main class, you'll need to replace this with an instance of it. The second argument is new Runnable() { ... } here we are actually creating the runnable. Whatever should be executed when the timer runs out, should go inside the curly braces. Lastly, the last parameter: this is the actual delay, measured in TICKS. This means, that if you wish to wait x seconds, you'll have to multiply x * 20, as a tick is equal 1/20 seconds, hence 5 seconds will be equal to 100 ticks.
If you know how to use lambdas, you can replace the anonymous class:
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, () -> player.sendMessage("The time has ran out!"), time);

Geotools com.vividsolutions.jts.geom.TopologyException: side location conflict

I get this exception and have no idea what do I do wrong.
I've created two polygons using linear ring.
Then I try to find do the intersect or not.
I get this exception:
com.vividsolutions.jts.geom.TopologyException: side location conflict [ (-1.7542192568359292E-100, 1.7542192568359284E-100, 0.0) ]
Here is the stackTrace:
com.vividsolutions.jts.geom.TopologyException: side location conflict [ (-1.7542192568359292E-100, 1.7542192568359284E-100, 0.0) ]
at com.vividsolutions.jts.geomgraph.EdgeEndStar.propagateSideLabels(EdgeEndStar.java:300)
at com.vividsolutions.jts.geomgraph.EdgeEndStar.computeLabelling(EdgeEndStar.java:139)
at com.vividsolutions.jts.operation.relate.RelateComputer.labelNodeEdges(RelateComputer.java:297)
at com.vividsolutions.jts.operation.relate.RelateComputer.computeIM(RelateComputer.java:132)
at com.vividsolutions.jts.operation.relate.RelateOp.getIntersectionMatrix(RelateOp.java:130)
at com.vividsolutions.jts.operation.relate.RelateOp.relate(RelateOp.java:75)
at com.vividsolutions.jts.geom.Geometry.relate(Geometry.java:1017)
at com.vividsolutions.jts.geom.Geometry.intersects(Geometry.java:769)
Exception happens in class EdgeEndStar:
//Debug.print(rightLoc != currLoc, this);
if (rightLoc != currLoc)
throw new TopologyException("side location conflict", e.getCoordinate());
if (leftLoc == Location.NONE) {
Assert.shouldNeverReachHere("found single null side (at " + e.getCoordinate() + ")");
}
currLoc = leftLoc;
Something wrong with edge wich have coordinates:
//coordinate: (-262.9001323617947, 313.3121772356619, 0.0)
//coordinate: (-232.77552855071107, 332.43790711803985, 0.0)
Please give me an idea about my mistake.
I've seen several posts in google with the same exception. Sometimes I do get this exception, sometimes not. Depends on the figure shape ofcourse :)
I called isValid() on both: linearRing and on Polygon. both objects are valid.
System.out.println("=== === ===");
LinearRing linearRing = geometryFactory.createLinearRing(coordinates.toArray(new Coordinate[coordinates.size()]));
IsValidOp isValidOp = new IsValidOp(linearRing);
System.out.println("LinearRing: closed?" + linearRing.isClosed() + " valid?" + linearRing.isValid() + " isValidOp.isValid(); " + isValidOp.isValid());
Polygon polygon =geometryFactory.createPolygon(linearRing, null);
isValidOp = new IsValidOp(polygon);
System.out.println("Polygon valid? " + polygon.isValid() +" isValidOp" + isValidOp.isValid());
return new BaseGeometry(polygon);
I have no idea what do I do wrong.
Update jts to 1.13 from 1.12
update getools to 10-SNAPSHOT from 9.0
then validation operation returned false.
Description said that the points in some locations were too close to each other and geotools thought that linear ring intersects itself.
I've truncated coodinates to 5 digits after dot and it helped. The precision was too high.
The problem is solved.

JInput "no jinput-dx8 in java.library.path" Error

Hi I'm trying to make a game in java that gives users the option to a joystick or gamepad to control movement. So I found something called "JInput" that is suppose to make it easy to detect all connected game controllers. The problem is that when I run it in Eclipse I get the following error: "java.lang.UnsatisfiedLinkError: no jinput-dx8 in java.library.path".
My code is the following:
import net.java.games.input.*;
public class ListControllers
{
public static void main(String[] args)
{
System.out.println("JInput version: " + Version.getVersion());
ControllerEnvironment ce =
ControllerEnvironment.getDefaultEnvironment();
Controller[] cs = ce.getControllers();
if (cs.length == 0) {
System.out.println("No controllers found");
System.exit(0);
}
// print the name and type for each controller
for (int i = 0; i < cs.length; i++)
System.out.println(i + ". " +
cs[i].getName() + ", " + cs[i].getType() );
} // end of main()
} // end of ListControllers class
I'm currently developing in Windows 7 environment. Any help would be really appreciated.
You should set java.library.path property to point to the directory containing native dlls of JInput.
You can do it by adding -Djava.library.path=x (where x is your path) to the command line or to the "VM arguments" field of "Run configurations" dialog in Eclipse.

Categories

Resources