קלט מקלדת ועכברKeyboard & mouse input
KeyListener, מצב מקשים לתנועה חלקה, עכבר, ומהירות שלא תלויה במחשב (delta time).
KeyListener, key state for smooth movement, the mouse, and speed that doesn't depend on the computer (delta time).
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- KeyListener: מקבל אירועים:
keyPressedכשלוחצים ו-keyReleasedכשעוזבים. ה-JPanel צריךsetFocusable(true)כדי לקבל אותם.KeyListener: Receives events:keyPressedon press andkeyReleasedon release. The JPanel needssetFocusable(true)to get them. - מצב מקשים: במקום להזיז בתוך
keyPressed(שחוזר בקפיצות), שומרים אילו מקשים לחוצים, ובכל טיק זזים לפיהם. התנועה חלקה ואפשר כמה מקשים יחד.key state: Instead of moving insidekeyPressed(which repeats in jumps), keep which keys are down, and move by them on every tick. Movement is smooth and several keys work together. - delta time: הזמן (בשניות) מאז הפריים הקודם. זזים
speed * dt, כך שבמחשב איטי (פחות פריימים) כל צעד גדול יותר, והמרחק בשנייה זהה.delta time: The time (in seconds) since the previous frame. Movespeed * dt, so on a slow computer (fewer frames) each step is bigger, and the distance per second is the same. - cooldown: זמן המתנה אחרי פעולה (כמו ירייה) לפני שמותר שוב. סופרים אותו אחורה עם
dt.cooldown: A wait after an action (like a shot) before it's allowed again. Count it down withdt.
02חללית שזזה עם המקלדתA spaceship moved by the keyboard
keyPressed ו-keyReleased רק מעדכנים את קבוצת המקשים הלחוצים. ה-Timer מחשב dt ומזיז לפי המקשים. נסו שני חצים יחד: אלכסון.
keyPressed and keyReleased only update the set of keys that are down. The Timer computes dt and moves by the keys. Try two arrows together: a diagonal.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
public class Main extends JPanel {
final Set<Integer> down = new HashSet<>();
double x = 200, y = 150;
long last = System.nanoTime();
Main() {
setPreferredSize(new Dimension(400, 300));
setFocusable(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
down.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
down.remove(e.getKeyCode());
}
});
new Timer(16, e -> {
long now = System.nanoTime();
double dt = (now - last) / 1e9;
last = now;
double speed = 180;
if (down.contains(KeyEvent.VK_LEFT)) x -= speed * dt;
if (down.contains(KeyEvent.VK_RIGHT)) x += speed * dt;
if (down.contains(KeyEvent.VK_UP)) y -= speed * dt;
if (down.contains(KeyEvent.VK_DOWN)) y += speed * dt;
repaint();
}).start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0x2D5BD0));
g.fillPolygon(new int[]{(int) x, (int) x - 15, (int) x + 15}, new int[]{(int) y - 20, (int) y + 15, (int) y + 15}, 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Spaceship");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Main());
f.pack();
f.setVisible(true);
}
}להרצה במחשב שלכם: חלון אמיתי שמקבל מקלדת. לחצו בתוכו ואז על החצים.
Run it on your computer: a real window taking the keyboard. Click inside it, then use the arrows.
03מצב מקשים בלי חלוןKey state without a window
הלוגיקה לבד: Input הוא מצב המקשים, ו-Ship.update(in, dt) זזה לפיו. שלושה טיקים ימינה של חצי שנייה במהירות 120 הם 180 פיקסלים.
The logic alone: Input is the key state, and Ship.update(in, dt) moves by it. Three half-second ticks to the right at speed 120 are 180 pixels.
public class Main {
public static void main(String[] args) {
Input in = new Input();
Ship s = new Ship(100, 100, 120);
in.right = true;
for (int i = 0; i < 3; i++) {
s.update(in, 0.5);
}
in.right = false;
in.up = true;
s.update(in, 0.5);
System.out.println(s.x + ", " + s.y);
}
}
class Input {
boolean left, right, up, down, fire;
}
class Ship {
double x, y;
final double speed;
Ship(double x, double y, double speed) {
this.x = x;
this.y = y;
this.speed = speed;
}
void update(Input in, double dt) {
if (in.left) {
x -= speed * dt;
}
if (in.right) {
x += speed * dt;
}
if (in.up) {
y -= speed * dt;
}
if (in.down) {
y += speed * dt;
}
}
}280.0, 40.0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04delta time: אותו מרחק בכל מחשבdelta time: the same distance on every computer
שנייה אחת ב-30 פריימים או ב-144: עם speed * dt מגיעים לאותו מקום.
One second at 30 frames or at 144: with speed * dt you end up in the same place.
public class Main {
static double travel(int fps, double speed, double seconds) {
double x = 0;
double dt = 1.0 / fps;
int frames = (int) Math.round(seconds * fps);
for (int i = 0; i < frames; i++) {
x += speed * dt;
}
return Math.round(x * 100) / 100.0;
}
public static void main(String[] args) {
System.out.println("30 fps: " + travel(30, 120, 1) + ", 144 fps: " + travel(144, 120, 1));
}
}30 fps: 120.0, 144 fps: 120.0
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
Gun עם cooldown של 0.3 שניות: כל עוד fire לחוץ, יורה כדור מהמיקום של החללית כשה-cooldown נגמר, וכל כדור עולה 400 לשנייה. החללית זזה ימינה ב-150. אחרי 10 פריימים של 0.1: ship x=350, bullets=4 ו-first bullet y=-80.
Gun with a 0.3-second cooldown: while fire is down, it shoots a bullet from the ship's position when the cooldown is over, and each bullet rises 400 per second. The ship moves right at 150. After 10 frames of 0.1: ship x=350, bullets=4 and first bullet y=-80.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.