Hello guys, I'm creating cannons. It will have: • A list of locations where the primed TNT can land • I will shoot the TNT when a button has been clicked • The primed TNT will go up and then land on a random location from the list The problem: The problem is the velocity of the TNT it just flies super far and never lands on the defined location. What I have: I will not give out the locations where it should land, because its pretty easy I store the button location as a key and then as value an ArrayList where 4 locations are in (HashMap). And then I return the HashMap. The part where I create the primed TNT: Code: TNTPrimed tnt = e.getClickedBlock().getWorld().spawn(part.get(CannonParts.FIRE), TNTPrimed.class); tnt.setFuseTicks(100); tnt.setVelocity(((Location) Cannons.getVoteHandler().activeMap.getCannonHitLoc().get(e.getClickedBlock().getLocation()) .toArray()[new Random().nextInt(4)]) .toVector() .add(new Vector(0, 2, 0) .normalize())); e.setCancelled(true);
It is extremely difficult to calculate a velocity vector that will result in your TNT landing on a specific place. But doing a "normalize().multiply(speed)" will help make things more sane. You could instead choose from 4 random vectors, and then tweak those vectors until they do about what you want.
Maybe try with this code: Code: public static Vector calculateVelocity(Vector from, Vector to, int heightGain) { // Gravity of a potion double gravity = 0.115; // Block locations int endGain = to.getBlockY() - from.getBlockY(); double horizDist = Math.sqrt(distanceSquared(from, to)); // Height gain int gain = heightGain; double maxGain = gain > (endGain + gain) ? gain : (endGain + gain); // Solve quadratic equation for velocity double a = -horizDist * horizDist / (4 * maxGain); double b = horizDist; double c = -endGain; double slope = -b / (2 * a) - Math.sqrt(b * b - 4 * a * c) / (2 * a); // Vertical velocity double vy = Math.sqrt(maxGain * gravity); // Horizontal velocity double vh = vy / slope; // Calculate horizontal direction int dx = to.getBlockX() - from.getBlockX(); int dz = to.getBlockZ() - from.getBlockZ(); double mag = Math.sqrt(dx * dx + dz * dz); double dirx = dx / mag; double dirz = dz / mag; // Horizontal velocity components double vx = vh * dirx; double vz = vh * dirz; return new Vector(vx, vy, vz); } private static double distanceSquared(Vector from, Vector to) { double dx = to.getBlockX() - from.getBlockX(); double dz = to.getBlockZ() - from.getBlockZ(); return dx * dx + dz * dz; }
+1 for the fanciest post ever :3 Sethbling, He probably got that from my post. Also, your gravity is wrong. that's the POTION GRAVITY.