Search Unity

Zoom in and out

Discussion in 'Scripting' started by Karen_M_2005, Jan 16, 2019.

  1. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    12
    Hello I tried to make zoom in and out script for my game but the problem is that it just rotates my camera and is not transforming my cam's position to the player. So please help!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Zoom : MonoBehaviour
    6. {
    7.  
    8.     void Update()
    9.     {
    10.         if (Input.GetAxis("Mouse ScrollWheel") <  0)
    11.         {
    12.             GetComponent<Transform>().localPosition = new Vector3(transform.localPosition.x - 2f, transform.localPosition.y - 2f, transform.localPosition.z);
    13.             transform.Rotate(2, 0, 0);
    14.         }
    15.         if (Input.GetAxis("Mouse ScrollWheel") > 0)
    16.         {
    17.             GetComponent<Transform>().localPosition = new Vector3(transform.localPosition.x + 2f, transform.localPosition.y +2f, transform.localPosition.z);
    18.             transform.Rotate(-2, 0, 0);
    19.         }
    20.     }
    21. }
     
  2. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    First of all, Every object in a Scene has a Transform so don't use GetComponent every time you want to access it, just use:
    Code (CSharp):
    1. transform.localPosition
    And your camera rotates because of:
    Code (CSharp):
    1. transform.Rotate
    in lines 13 and 18
     
  3. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    12
    No I want it rotate but zoom camera in too at the same time.
     
  4. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
  5. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    12
    Nah I tried but it seems to be kinda weird. I want to make it zoom by transforming it's position I don't want to mess with field of view.
     
  6. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,639
    Just like you can use transform.Rotate to rotate, you can also use transform.Translate to move an object.