在创建点和鼠标点之间缩放对象

时间:2015-06-04 21:44:12

标签: c# unity3d

我创建了一个脚本,当我点击地形时,它会在该位置创建一个立方体预制件。

当我在屏幕上移动鼠标时,预制件会执行LookAt(),因此立方体会不断查看鼠标所在的地形。我能够正常工作的是,当我拖动鼠标时,立方体应该沿着它所做的Z Axis缩放,但它会在创建它的中间缩放。

所以我补充说:

currentObj.transform.position = new Vector3(trs.position.x, trs.position.y, startPosition.z - distance);

这使我感到奇怪,我无法解释,但这是不正确的。我想要的是立方体有一个面在哪里创建,另一面在鼠标位置(沿着Z Axis缩放)。

if(started)块是问题所在的代码:

public class BridgeCtrl : MonoBehaviour {

    public GameObject bridge;

    GameObject currentObj;

    Vector3 mouseWorldPosition;
    Vector3 startPosition;

    bool mouseDown = false;
    bool started = false;
    bool bridgeBuilt = true;

    // Update is called once per frame
    void Update () {
        // Preview Bridge
        if(started){
            RaycastHit hit = GetWorldPosition();
            if(!hit.Equals(null)){
                currentObj.transform.LookAt(hit.point);
                Transform trs = currentObj.transform;
                float distance = Vector3.Distance(trs.position, hit.point);
                currentObj.transform.localScale = new Vector3(trs.localScale.x, trs.localScale.y, distance);
                currentObj.transform.position = new Vector3(trs.position.x, trs.position.y, startPosition.z - distance);
            }
        }

        // Start Bridge
        if(Input.GetMouseButtonDown(0) && !started){
            started = true;
            RaycastHit hit = GetWorldPosition();
            if(!hit.Equals(null)){
                startPosition = hit.point;
                currentObj = GameObject.Instantiate(bridge, startPosition, Quaternion.identity) as GameObject;
            }
        }
        // End Bridge
        else if(Input.GetMouseButtonDown(0) && started){
            started = false;
        }

        if(Input.GetKeyDown(KeyCode.Escape) && started){
            if(!currentObj.Equals(null)){
                GameObject.Destroy(currentObj);
                started = false;
            }
        }
    }

    RaycastHit GetWorldPosition(){
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Physics.Raycast(ray, out hit);
        return hit;
    }
}

那么,我怎样才能得到它,以便它在对象的创建点和鼠标指针之间沿Z Axis缩放?

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用Ray?

Ray ray = new Ray(startPosition, (startPosition - hit.point));
currentObj.transform.position = ray.GetPoint(distance/2);