Skip to content

Instantly share code, notes, and snippets.

@22shubh22
Created April 21, 2020 16:32
Show Gist options
  • Save 22shubh22/42644990a0d80e50a0e548a9866f755a to your computer and use it in GitHub Desktop.
Save 22shubh22/42644990a0d80e50a0e548a9866f755a to your computer and use it in GitHub Desktop.
Rotation of Object around it's centre
use tetra::graphics::{self, Color, Texture};
use tetra::input::{self, Key};
use tetra::math::Vec2;
use tetra::window;
use tetra::{Context, ContextBuilder, State};
const WINDOW_WIDTH: f32 = 640.0;
const WINDOW_HEIGHT: f32 = 480.0;
const ANGLE: f32 = 0.1;
fn main() -> tetra::Result{
ContextBuilder::new("Rotation", WINDOW_WIDTH as i32, WINDOW_HEIGHT as i32)
.resizable(true)
.quit_on_escape(true)
.build()?
.run(GameState::new)
}
struct Entity {
texture: Texture,
position: Vec2<f32>,
facing: f32,
}
impl Entity {
fn new(texture: Texture, position: Vec2<f32>) -> Entity {
Entity {
texture,
position,
facing: 0.,
}
}
fn width(&self) -> f32 {
self.texture.width() as f32
}
fn height(&self) -> f32 {
self.texture.height() as f32
}
// Setting origin
fn origin(&self) -> Vec2<f32> {
Vec2::new (
self.width() / 2.0,
self.height() / 2.0,
)
}
}
struct GameState {
image: Entity,
}
impl GameState {
fn new(ctx: &mut Context) -> tetra::Result<GameState> {
let tex = Texture::new(ctx, "./resources/player.png")?;
let pos = Vec2::new(
WINDOW_WIDTH / 2.0,
WINDOW_HEIGHT / 2.0,
);
Ok(GameState {
image: Entity::new(tex, pos),
})
}
}
impl State for GameState {
fn draw(&mut self, ctx: &mut Context) -> tetra::Result {
graphics::clear(ctx, Color::rgb(0., 0., 0.));
let drawparams = graphics::DrawParams::new()
.origin(self.image.origin())
.position(self.image.position)
//.scale(Vec2::new(1.0,2.0))
//.position(Vec2::zero())
.rotation(self.image.facing);
graphics::draw(ctx, &self.image.texture, drawparams);
Ok(())
}
fn update(&mut self, ctx: &mut Context) -> tetra::Result {
if input::is_key_down(ctx, Key::Left) {
self.image.facing += ANGLE;
}
if input::is_key_down(ctx, Key::Right) {
self.image.facing -= ANGLE;
}
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment