- Home /
Question by
joshua-lyness · May 21, 2015 at 05:12 PM ·
rotationinstantiatevector3
Instantiating relative to rotation of object
I have the following script which should make the camera rotate around a point in front of it equal to the distance from the height to the ground and at the ground level. Whist this works when the camera is rotated at 0 degrees, if you rotate the camera, this no longer works:
using System.Collections;
public class cameraController : MonoBehaviour
{
public float cameraHeight;
public int translateSensitivity = 50;
public int zoomSensitivity = 50;
public float previousMousePositionY;
public float previousMousePositionX;
public Vector3 pivotPoint;
public float rotateAmountX;
public float rotateAmountY;
public GameObject sphere;
void Update()
{
//raycast towards ground, to return the height of the camera
RaycastHit hit;
if(Physics.Raycast(transform.position, -Vector3.up, out hit))
{
if(hit.collider.tag == "placableGround")
{
cameraHeight = hit.distance;
}
}
//translation by arrow keys
if(Input.GetAxis("Horizontal") != 0)
{
transform.Translate(Input.GetAxis("Horizontal") * translateSensitivity * cameraHeight/10 * Time.deltaTime, 0, 0);
}
if(Input.GetAxis("Vertical") != 0)
{
transform.Translate(0, 0, Input.GetAxis("Vertical") * translateSensitivity * cameraHeight/10 * Time.deltaTime);
}
//camera zoom
if(Input.GetAxis("Mouse ScrollWheel") != 0)
{
transform.Translate( 0, 0, Input.GetAxis("Mouse ScrollWheel") * cameraHeight * zoomSensitivity * Time.deltaTime);
}
//camera rotation along x axis at a height and distance of that from the ground
if(Input.GetMouseButtonDown(2))
{
previousMousePositionY = Input.mousePosition.y;
previousMousePositionX = Input.mousePosition.x;
transform.Rotate(0, 0, -transform.eulerAngles.z);
pivotPoint = new Vector3(transform.position.x, transform.up.y - cameraHeight, transform.forward.z + (cameraHeight * 2));
Instantiate(sphere, pivotPoint, Quaternion.identity);
}
if(Input.GetMouseButton(2))
{
rotateAmountX = Input.mousePosition.y - previousMousePositionY;
transform.Rotate(0, 0, -transform.eulerAngles.z);
transform.RotateAround(pivotPoint, transform.right, rotateAmountX);
previousMousePositionY = Input.mousePosition.y;
}
if(Input.GetMouseButton(2))
{
rotateAmountY = Input.mousePosition.x - previousMousePositionX;
transform.RotateAround(pivotPoint, Vector3.up, rotateAmountY);
previousMousePositionX = Input.mousePosition.x;
}
}
}
The point is being instantiated at the co ordinates of the camera as expected, but not offset relative to the camera's rotation, instead it is adding the camera height of pivotPoint to the world axis....
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613200134im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get rotation from hit object 1 Answer
How to transform rotation of a vector 3? 1 Answer
I need help with rotation 2 Answers
Instantiating objects at position 1 Answer
Rotating wrong 0 Answers