Отражение спрайта / врага p5. js JavaScipt - PullRequest
0 голосов
/ 21 февраля 2020

Я делал простую маленькую платформерную игру, используя p5. js. Я новичок в кодировании и JavaScript и не могу понять, как перевернуть изображение моего спрайта в направлении, в котором он движется?

Пока что у меня есть это (я извиняюсь, если это грязно, и у меня есть закончил рисовать, но вы поняли):

function enemy(x, y, range)
{
    this.x = x;
    this.y = y;
    this.range = range;
    
    this.currentX = x;
    this.inc = 1;
    
    this.update = function()
    {
        this.currentX += this.inc;
        
        if(this.currentX >= this.x + this.range)
            {
                this.inc = -1;   
            }
        else if(this.currentX < this.x)
            {
                this.inc = 1;
            }
    }
    
    this.draw = function()
    {
        this.update();
        
        fill(0, 0, 0);
        noStroke();
        ellipse(this.currentX, this.y, 40, 30);
        triangle(this.currentX + 15, this.y - 10, 
                 this.currentX + 50, this.y + 5, 
                 this.currentX + 15, this.y + 10);
        ellipse(this.currentX + 20, this.y, 20 ,20);
        ellipse(this.currentX + 15, this.y - 10, 15, 15);
    }
    
    this.checkContact = function(gc_x, gc_y)
    {
        var d = dist(gc_x, gc_y, this.currentX, this.y)
        
        if(d < 20)
            {
                return true;
            }
        return false;
    }
}

1 Ответ

0 голосов
/ 21 февраля 2020

Поскольку враг движется только по оси X, быстрое и грязное исправление заключается в изменении всех значений смещения указанной оси в зависимости от направления построения:

function enemy(x, y, range)
{
    this.x = x;
    this.y = y;
    this.range = range;
    
    this.currentX = x;
    this.inc = 2;
    this.direction = 1  // new attribute
 
    this.update = function()
    {
        this.currentX += this.inc;
        
        if(this.currentX >= this.x + this.range)
            {
                this.inc = -2;
                this.direction = -1
            }
        else if(this.currentX < this.x)
            {
                this.inc = 2;
                this.direction = 1
            }
    }


    this.display = function()
    {
        this.update();

        fill(0, 0, 0);
        noStroke();
        ellipse(this.currentX, this.y, 40, 30);
        triangle(this.currentX + (this.direction*15), this.y - 10, 
                 this.currentX + (this.direction*50), this.y + 5, 
                 this.currentX + (this.direction*15), this.y + 10);
        ellipse(this.currentX + (this.direction*20), this.y, 20 ,20);
        ellipse(this.currentX + (this.direction*15), this.y - 10, 15, 15);
    }
}

let e = new enemy(100, 50, 200)

const setup = function(){
  createCanvas(400, 150)
}

const draw = function(){
  background(200)
  e.display()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.min.js"></script>
...