首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使物体掉头而向相反的方向移动?

如何使物体掉头而向相反的方向移动?
EN

Stack Overflow用户
提问于 2013-09-18 11:39:37
回答 5查看 1.7K关注 0票数 0

考虑到出界位置是6和-6。

我想让这艘船掉头朝相反的方向移动。

这是我的密码..。它仍然不能百分之百地发挥我想要的效果。我很好奇,想看看有没有人想过如何改进。这是我的代码的逻辑。

代码语言:javascript
代码运行次数:0
运行
复制
//If the ship hits a boundary it turns around and moves in the opp.
//direction. To do this, the ship's velocty should be flipped from a 
//negative into a positive number, or from pos to neg if boundary
//is hit.

//if ship position is -5 at velocity -1 new ship pos is -6
//if ship position is -6 at velocity -1 new ship velocity is +1
//                                      new ship position is +5

这是我的代码:

代码语言:javascript
代码运行次数:0
运行
复制
public void move() 
{
    position = velocity + position;

    if (position > 5)
    {
        velocity = -velocity;
    }
    else if (position < -5)
    {
        velocity = +velocity;
    }
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-09-18 11:52:02

代码velocity = +velocity;不会将负速度改变为正速度。这相当于将速度与+1相乘,它不会改变符号。

当超出边界时,要翻转速度的符号,您需要总是乘以-1

它不太清楚的界限是这么低,我假设他们是6和-6。

代码语言:javascript
代码运行次数:0
运行
复制
position += velocity;
//make sure the ship cannot go further than the bounds
//but also make sure that the ship doesn't stand still with large velocities
if (position > 6)
{
    velocity = -velocity;
    position = 6;
}
if (position < -6)
{
    velocity = -velocity;
    position = -6;
}
票数 1
EN

Stack Overflow用户

发布于 2013-09-18 11:51:41

你可以这样做:

代码语言:javascript
代码运行次数:0
运行
复制
public void move() 
    {
    //first check where the next move will be:
    if ((position + velocity) > 5 || (position + velocity) < -5){

        // Here we change direction (the velocity is multiplied for -1)
        velocity *= -1;

    }

    position += velocity;
}
票数 1
EN

Stack Overflow用户

发布于 2013-09-18 11:47:44

当它到达一个边界时,将速度乘以-1。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18871247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档