I created a script that when I click on the terrain, It creates a cube prefab at that position.
When I move my mouse around the screen, the prefab does a LookAt() so the cube constantly looks at the terrain where the mouse is. What I can't get to work quite right is when I drag the mouse the cube should scale along the Z Axis Which it does but it scales at the middle of where it was created.
So I added this:
currentObj.transform.position = new Vector3(trs.position.x, trs.position.y, startPosition.z - distance);
Which moves it it a weird way that I can't explain, but it isn't correct. What I would like is for the cube to have one face where it was created and the other face at the location of the mouse (scaled along the Z Axis).
The if(started) block is where the issue lies in the code:
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;
}
}
So, how can I get this so it scales along the Z Axis between the creation point of the object and the mouse pointer?