libgdx学习记录5——演员Actor

时间:2023-08-28 15:33:56

Actor也是libgdx中非常重要的一个元素,一般与stage配合一起使用。Actor能够设置大小,位置,旋转和动画等。

我们自定义的Actor一般需要继承于Actor,并且重写其中的act和draw方法。

自定义的actor是一个图片。

 class MyActor extends Actor{
TextureRegion region; public MyActor(){
Texture texture = new Texture( Gdx.files.internal( "data/badlogic.jpg" ) );
region = new TextureRegion( texture );
setSize( region.getRegionWidth()/2, region.getRegionHeight()/2 );
setOrigin( getWidth()/2, getHeight()/2 );
} @Override
public void act(float delta) {
// TODO Auto-generated method stub
super.act(delta);
} @Override
public void draw(SpriteBatch batch, float parentAlpha) {
// TODO Auto-generated method stub
batch.draw( region, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation() );
super.draw(batch, parentAlpha);
} public void dispose(){
region.getTexture().dispose();
}
}

主类,包含stage:

 package com.fxb.newtest;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image; public class Lib004_Actor extends ApplicationAdapter{ BitmapFont font;
Stage stage;
MyActor actor;
//String strShow;
int count; @Override
public void create() {
// TODO Auto-generated method stub
stage = new Stage();
font = new BitmapFont();
font.setColor( Color.DARK_GRAY ); actor = new MyActor();
stage.addActor( actor );
actor.setPosition( stage.getWidth()/2-actor.getWidth()/2, stage.getHeight()/2-actor.getHeight()/2 ); count = 0;
actor.addListener(new InputListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
count++;
return true;
}
}); Gdx.input.setInputProcessor( stage );
} @Override
public void render() {
// TODO Auto-generated method stub
Gdx.gl.glClearColor( 1, 1, 1, 1 );
Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); stage.act();
stage.draw(); SpriteBatch batch = stage.getSpriteBatch();
batch.begin();
//batch.draw( font, actor.getX(), );
font.draw( batch, "You have clicked " + count + " times!", actor.getX()-25, actor.getY()-20 );
batch.end(); } @Override
public void dispose() {
// TODO Auto-generated method stub
super.dispose();
} }

运行结果:

libgdx学习记录5——演员Actor