翻译对象直到碰撞

时间:2017-09-06 08:09:32

标签: c# unity3d game-physics unity2d

我希望我的物体永远在目标的方向上移动,或直到它碰撞,碰撞部分我已经处理过了;但是,我在运动部件方面遇到了问题。

我首先尝试使用这些代码行来旋转目标

Vector2 diff = target - transform.position;
float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0.0f, 0.0f, angle);

这很完美,我的物体按照我想要的方向旋转。 在我的Update方法中,我有以下

if (isMoving)
    {
        Vector2 f = transform.forward;
        transform.position = Vector3.MoveTowards(transform.position, target + Vector3.forward, speed * Time.deltaTime);
    }

现在这个已经运行,但未能完成目标,我知道为什么,它有意义,但不确定如何解决它。物体以正确的方向移动到该点,但我不希望它停在目标上,我希望它继续前进。

我也试过

rb.MovePosition(rb.position + f * Time.deltaTime * speed);

rb是一个刚体2D

以及

rb.AddForce(rb.position + f * Time.deltaTime * speed);

但在这两种情况下,对象都会旋转但从不移动

我还使用了翻译和与MovePosition相同的行为

P.S。这是一款2D游戏

1 个答案:

答案 0 :(得分:0)

在浏览互联网后,我没有发现任何真正能满足我要求的东西,你无法永久地翻译运动物体(显然你必须处理对象应该在某些时候被破坏或者什么,但那不是问题)。所以我继续前进,决定编写自己的库来简化这一过程。我能够使用线方程实现我的目标。很简单,我采取了这些步骤来解决我的问题。

  1. 一开始我得到2分之间的斜率
  2. 计算y轴截距
  3. 使用具有固定X值的线方程转换对象(步骤),每个x值找到相应的y值并将对象转换为它。
  4. 在FixedUpdate中重复步骤3,就是这样。
  5. 当然还有更多内容,处理x = 0的情况,这将给出斜率的0除法或y = 0等等......我解决了库中的所有问题。对于任何有兴趣的人,您可以在EasyMovement

    查看

    如果你不想要这个库,那么这里就是一个简单的代码。

     //Start by Defining 5 variables
     private float slope;
     private float yintercept;
     private float nextY;
     private float nextX;
     private float step;
     private Vector3 direction;    //This is your direction position, can be anything (e.g. a mouse click)
    

    开始方法

    //step can be anything you want, how many steps you want your object to take, I prefer 0.5f
    step = 0.5f;
    
    //Calculate Slope => (y1-y2)/(x1-x2)
    slope = (gameObject.transform.position.y - direction.y) / (gameObject.transform.position.x - direction.x);
    
    //Calculate Y Intercept => y1-x1*m
    yintercept = gameObject.transform.position.y - (gameObject.transform.position.x * slope);
    

    现在位于 FixedUpdate

    //Start by calculating the nextX value
    //nextX
    if (direction.x > 0)
        nextX = gameObject.transform.position.x + step;
    else
        nextX = gameObject.transform.position.x - step;
    
    //Now calcuate nextY by plugging everything into a line equation
    nextY = (slope * nextX) + yintercept;
    
    //Finally move your object into the new coordinates
    gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, new Vector3(nextX, nextY, 0), speed * Time.deltaTime);
    

    请记住,这不会造成繁重的工作,需要考虑很多条件。