- Home /
How to Move Top Down Camera Towards Game Object on Touch?
I have a top down camera that I want to move to a game object when that game object is touched. The camera needs to move along it's Z and X axis only.
I think that transform.Translate is a good starting point, but not sure or not.
Any ideas on how to do this?
Thanks in advance.
Comment
Best Answer
Answer by robertbu · Dec 10, 2013 at 06:10 AM
Here is some starter code for you. The script must be attached to the camera. The code will move the camera over any object that is tagged 'CameraTarget'. It works on a mouse click, so you can test and play with it in the editor. I leave converting it to touch for you to do.
#pragma strict
var pos : Vector3;
var speed = 2.0;
function Start() {
pos = transform.position;
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit) && hit.collider.tag == "CameraTarget") {
pos = hit.transform.position;
pos.y = transform.position.y;
}
}
transform.position = Vector3.MoveTowards(transform.position, pos, speed * Time.deltaTime);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613123834im_/https://answers.unity.com/themes/thub/images/avi.jpg)