I'm using the script stated below to move a spray bottle around a head.
The code works fine: I have assigned the script to the spray bottle, and I have set the head as the target.
However, I was not happy with the center that Unity seems to use for the spray bottle. The spray bottle never perfectly aimed at the center of the head.
To find out what is going on here, I added a long sphere to the spray bottle. Then I moved the sphere until it would perfectly visualize the center that Unity uses. As once can see, Unity uses the bottom of the spray bottle as its center. I have uploaded a video here to show the effect.
I imagined that I need to tell the script that the center of the spray bottle is different. I would have to include an offset (I guess a Vector3) in order to set the nozzle as the center.
I haven't been able to find out how to plug this "offset" into the script.
Can anybody tell me where / how I could do that?
Thank you very much!
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour
{
public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
private Rigidbody rigidbody;
float x = 0.0f;
float y = 0.0f;
// Use this for initialization
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
}
void LateUpdate()
{
if (target)
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
Quaternion rotation = Quaternion.Euler(y, x, 0);
Vector3 nTargetPos = target.position + new Vector3(0, 0.1f, 0);//10 centimetres lower. The original target.position's center would be around the nose. Instead I want the forehead to be the center, that's why I add 10 centimeters to the y position.
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + nTargetPos;
transform.rotation = rotation * Quaternion.Euler(0, -90, 0);//compensate for the fact that the spray bottle should face the head (requiring yaw to be yaw-=90)
transform.position = position;
}
}