【问题标题】:Vector3.MoveTowards while also following cursor?Vector3.MoveTowards 同时也跟随光标?
【发布时间】:2018-05-08 11:05:17
【问题描述】:

我正在制作一个跟随鼠标位置的角色。

我也有正在实例化的敌人,并希望该角色向敌人的位置移动,但比敌人高几英尺。

由于我的角色是一个飞行的敌人,我不确定如何使用统一移动。 当我的敌人被摧毁时,我还希望角色继续跟随光标。

public class FollowCursor : MonoBehaviour 
{

    // Use this for initialization
    void Start ()
    {   
    }

    // Update is called once per frame
    void Update () 
    {
        if(GameObject.FindWithTag("Enemy"))
        {   
            transform.position = Vector3.MoveTowards.GameObject.FindWithTag("Enemy").transform.position;
        }
        else
        {   
            transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
        }
    }
}                        

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    我了解到您希望向飞行的敌人移动和/或让飞行的敌人向您的角色移动。

    我也了解到您希望使用 MoveTowards 方法来执行此操作。

    您应该可以通过忽略 Y 位置或将其设置为固定值来做到这一点。

    像这样。

    //Method used: Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta); 
    
    //Set movespeed/steps
    float speed = 5f;
    float step = speed * Time.deltaTime;
    
    //Define y position
    float yourFixedYValue = 8.75f;
    
    //Find target
    Vector3 enemyPosition = GameObject.FindWithTag("Enemy").transform.position;
    Vector3 target = new Vector3(enemyPosition.x, yourFixedYValue, enemyPosition.z);
    
    //Move from current position towards target with step increment.
    transform.position = Vector3.MoveTowards(transform.position, target, step);
    

    如果这没有回答您的问题,请详细说明您的意思。

    编辑:

    要向鼠标移动,您可以在 Update 方法中使用类似这样的 Raycast。

    if (Input.GetMouseButtonDown(0)) 
    { //If left mouse clicked
        RaycastHit hit; 
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Fire ray towards where mouse is clicked, from camera.
        if (Physics.Raycast(ray, out hit))  //If hit something
            target = hit.point; //point is a vector3 //hit.point becomes your target
    }
    

    那个“东西”可以是任何对撞机,也可以是敌人。所以可以用来在一般情况下四处走动和向敌人移动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-21
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 2020-09-04
      相关资源
      最近更新 更多