I’ve been working on a RTS game and I wanted to be able to zoom in with the mouse wheel toward the mouse.
In a lot of RTS games, you can hover over a unit, scroll upwards, and end up with the unit in the middle of your screen very zoomed.
That’s what I’m trying to accomplish.
Here's my World.java: [spoiler]
package net.space.render;
import java.util.ArrayList;
import net.space.entity.Entity;
import net.space.main.ReducedSpace;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Graphics;
public class World {
public float zX=0, zY=0;
private float zoomLevel;
private static final float zoomStep=0.0625f;
private ArrayList<Entity> entities = new ArrayList<Entity>();
public void draw(Graphics g) {
g.scale(getZoomLevel(), getZoomLevel());
g.translate(zX, zY);
for(Entity e:entities) {
if(e!=null) {
e.draw(g);
}
}
}
public float getZoomLevel() {
return zoomLevel;
}
public void setZoomLevel(float z) {
zoomLevel = z;
}
public void mouseWheelZoom() {
int mouseWheel = Mouse.getDWheel();
if(mouseWheel==0) {
return;
}
boolean positive = mouseWheel>0;
if (positive) {
addZoomLevel(zoomStep);
}
else {
addZoomLevel(-zoomStep);
}
if(mouseWheel != 0) {
zX+=(Mouse.getX()*(mouseWheel/240f))/zoomLevel;
zY-=((ReducedSpace.h-Mouse.getY())*(mouseWheel/240f))/zoomLevel;
}
System.out.println("RAWX: "+Mouse.getX()+"\nRAWY: "+Mouse.getY()+"\nEXP: "+mouseWheel+"|"+(mouseWheel/240f)+"\nWHEEL: "+mouseWheel);
System.out.println("X: "+zX+"\nY: "+zY);
}
public void addZoomLevel(float a) {
zoomLevel+=a;
if(zoomLevel>1.2375f) {
zoomLevel=1.2375f;
}
if(zoomLevel<.1f) {
zoomLevel=.1f;
}
}
public int addEntity(Entity e) {
entities.add(e);
return entities.size();
}
public void removeEntity(int index) {
entities.set(index, null);
}
public void removeEntity(String name) {
for(int i=0;i<entities.size();i++) {
if(entities.get(i).name.matches(name)) {
removeEntity(i);
return;
}
}
}
public Entity getEntity(int index) {
return entities.get(index);
}
public Entity getEntity(String name) {
for(int i=0;i<entities.size();i++) {
if(entities.get(i).name.matches(name)) {
return getEntity(i);
}
}
return null;
}
}
[/spoiler]
Thanks for any help!