- Home /
Jump to position in front of an object
I want to my camera to jump to a position right in front of a particular object so you can "inspect that object". I currently have it set up that with raycasting you and point and select an object and jump to its position. However I wish to jump to a position just short of that object so that the player can look at it close up. I dont want to use a camera zoom function either. Any ideas for this? I know you can get the distance between two vectors and am wondering if I could somehow use that to travel a certain amount of that distance toward the object? Here is what I have in my code so far. I need this to go in the camJump function.
// Update is called once per frame void Update () { ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out hit)) {
print ("There is something in front of the object");
myTarget = hit.collider.gameObject;
//float dist = Vector3.Distance(myTarget.transform.position, transform.position);
//print("Distance to other: " + dist);
}
else {
if(myTarget != null)
myTarget = null;
print ("Theres nothing ahead");
}
if (Input.GetKeyUp (KeyCode.Space)){
CamJump();
}
}
void CamJump(){
if(!zoomed && myTarget != null){
oldPos = transform.position;
transform.position = myTarget.transform.position; //maybe myTarget.transform.position - 1? or something
//transform.LookAt(myTarget);
zoomed = true;
}
else{
transform.position = oldPos;
zoomed = false;
}
}
Answer by Noah Dyer · Jan 13, 2015 at 08:13 PM
One easy way is to use transform.forward, and back up from that.
oldPos = transform.position;
transform.position = myTarget.transform.position - transform.forward*someNumber;
forward is going to be a unit vector, so you'll probably need to scale it. someNumber can either be a hardcoded number based on your experimentation, or a dynamic value based on properties of myTarget (which will allow you to achieve better zoom for obejcts of wildly different size).
Hope that helps!
Your answer
Follow this Question
Related Questions
Move an object to a specific distance 0 Answers
How to stop transform.Translate instantly ? 1 Answer
Extreme Beginner Scripting Question 1 Answer
How to get translation from matrix? 1 Answer
Problems with pathfinding algorithm 0 Answers