Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - 碰撞后如何保持玩家位置?(How to keep player position after collision?)

Im making a game in canvas and I have included a library to deal with collision for me.

(我在画布上制作游戏,并且提供了一个库来为我处理碰撞。)

The collision is working perfectly, but I am not really sure how to "freeze" the player in place and not allow movement in that direction after colliding.

(碰撞工作正常,但是我不确定如何将玩家“冻结”到位,并且在碰撞后不允许沿该方向移动。)

Can anyone help me out ?

(谁能帮我吗 ?)

What I tried :

(我试过了)

  moveRight() {
    this.pp.x = this.position.x;
    this.position.x += 20;
  }
  moveLeft() {
    this.pp.x = this.position.x;
    this.position.x -= 20;
  }
  moveUp() {
    this.pp.y = this.position.y;
    this.position.y += 20;
  }
  moveDown() {
    this.pp.y = this.position.y;
    this.position.y -= 20;
  }

I tried keeping track of "previous position" and set it to that on collision, but it's behaving really strange, doesn't really work.

(我尝试跟踪“先前位置”并将其设置为发生碰撞时的位置,但是它的行为确实很奇怪,实际上并不起作用。)

Ideally, I would like to make a stop() function in my player class that I would call upon player colliding with the world.

(理想情况下,我想在我的玩家类中创建一个stop()函数,呼吁玩家与世界碰撞。)

Thanks so much, any help is greatly appreciated !

(非常感谢,非常感谢您的帮助!)

!

(!)

!

(!)

  ask by sillenius translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to do it is to have 20 as a property of your class.

(一种实现方法是将20作为类的property 。)

This property would be a " speed " property.

(此属性将是“ speed ”属性。)

You can then access it using " this.speed ".

(然后,您可以使用“ this.speed ”访问它。)

Once you detect a collision set the speed to 0 and you will "freeze" your character.

(一旦检测到碰撞,将速度设置为0 ,您将“冻结”角色。)

For example moveRight would become

(例如moveRight将变为)

moveRight() {
    this.pp.x = this.position.x;
    this.position.x += this.speed;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...