java游戏上下左右移动_java,谁能写个代码,能监听上下左右键的!我想实现游戏角色的左右移动!在线等!不要复制百度上的,...

展开全部

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CelMove extends JFrame {

e68a8462616964757a686964616f31333337616538private static final long serialVersionUID = 3171295325956127838L;

CelJPanel cjp;

static int width = 500, height = 380;

public CelMove() {

// 设置方块的初始位置

cjp = new CelJPanel(width / 2, height / 2);

// 设置方块的背景颜色

cjp.setBackground(Color.YELLOW);

// 设置绘制方块的面板的大小

cjp.setSize(width, height);

// 添加鼠标事件 让方块跟着鼠标移动

this.addMouseMotionListener(new MouseMotionListener() {

@Override

public void mouseMoved(MouseEvent e) {

Point p = e.getPoint();//得到鼠标点击的位置

cjp.lx = p.x;//设置当方块x坐标=点击的x作弊

if (cjp.lx > width - 28) {// 28是空出来的一个左右边框大小.为了不让方块移动出了界面

cjp.lx = width - 28;// 如果超过边界.就设置方块的x ,回到边框内

}

if (cjp.lx 

cjp.lx = 0;

}

cjp.ly = p.y;

if (cjp.ly > height - 50) {// 50是空出来的一个上下边框大小.为了不让方块移动出了界面

cjp.ly = height - 50;

}

if (cjp.ly 

cjp.ly = 0;

}

// lx,ly坐标设置完成,才执行repaint()重绘

cjp.repaint();

}

// 当拖动鼠标的时候..

@Override

public void mouseDragged(MouseEvent e) {

}

});

// 添加一个键盘事件

this.addKeyListener(new KeyAdapter() {

@Override

public void keyPressed(KeyEvent e) {

int speed = 10;

// S 和 下箭头 可以向下移动

if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN) {

// 这里没有写是否出界的代码.你可以先判断移动后是否会超过边框

cjp.ly = cjp.ly + speed;

cjp.repaint();

}

// W 和 上箭头 可以向上移动

if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP) {

cjp.ly = cjp.ly - speed;

cjp.repaint();

}

// A 和 左箭头 可以向左移动

if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT) {

cjp.lx = cjp.lx - speed;

cjp.repaint();

}

// D 和 右箭头 可以向右移动

if (e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT) {

cjp.lx = cjp.lx + speed;

cjp.repaint();

}

}

});

// 设置主窗口的相关属性

this.setLayout(null);

this.add(cjp);

this.setTitle("移动方块");

this.setLocation(150, 100);

this.setSize(width, height);

this.setResizable(false);

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

this.setVisible(true);

}

public static void main(String[] args) {

new CelMove();

}

// 绘制方块的类

class CelJPanel extends JPanel {

int lx, ly;

public CelJPanel(int lx, int ly) {

super();

this.lx = lx;

this.ly = ly;

}

@Override

public void paint(Graphics g) {

super.paint(g);

g.setColor(Color.RED);

g.fillRect(lx, ly, 20, 20);

}

}

}

你参考下吧,很久前写的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值