【问题标题】:sprite.SetScale Function not working (libGDX)sprite.SetScale 函数不起作用(libGDX)
【发布时间】:2016-03-24 01:01:56
【问题描述】:

您好,我正在尝试使用 libGDX 制作一个简单的游戏,但我在使用 sprite 类时遇到了一些问题,这是我的代码:

package com.carebearer;

import com.badlogic.gdx.ApplicationAdapter;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;


public class demo extends ApplicationAdapter{
    SpriteBatch batch;
    Texture img;
    Sprite sprite;

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("hello.png"); 
        sprite = new Sprite(img);
        sprite.setScale(.5f);
        sprite.setPosition(Gdx.graphics.getWidth()/2 - sprite.getWidth()/2, 
                           Gdx.graphics.getHeight()/2 - sprite.getHeight()/2);

    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1); //RGBAlpha, 1 = 100%
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(sprite, sprite.getX(), sprite.getY()); 
        batch.end();
    } 
   }

问题在于 setScale 函数。

无论我是否使用 setScale 绘制的精灵都保持不变(它基本上什么都不做)。我想要它做的是将 Sprite 的大小减半

我很确定我遗漏了一些明显的东西,但我被这个问题困扰的时间比我想承认的要长。

【问题讨论】:

  • 好吧,经过数小时的尝试,我在发布几分钟后设法找到了我的错误。为了使缩放起作用,您需要将其发送到batch.draw,因为如果您不指定它,该函数将默认使用图像原始比例。以下是对代码所做的更改。 > batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getWidth()/2,sprite.getHeight()/2,sprite.getWidth(),sprite.getHeight(),sprite.getScaleX (),sprite.getScaleY(),sprite.getRotation());
  • 或者使用精灵在批处理的帮助下绘制自己。 sprite.draw(batch) 这是绘制精灵的预期方式。

标签: java libgdx sprite


【解决方案1】:

您没有正确使用 Sprite。使用sprite.draw(batch) 而不是batch.draw(sprite, ...)。如果您使用batch.draw,则 SpriteBatch 将 Sprite 视为一个哑 TextureRegion 并忽略其所有位置和大小参数。如果你像在评论中那样手动应用它们,你还不如使用重量更轻的 TextureRegion 而不是 SpriteBatch。

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多