Move, Zoom and Rotate Camera – Unity3D (C#)

Move, Zoom and Rotate Camera – Unity3D (C#)

Move: It is same as moving character. Just use keyboard buttons and move camera with a float speed variable.


Zoom: To zoom with scroll wheel, we need scroll wheel input to zoom in or zoom out.

Rotate: I will give an example with mouse button pressed but you can change it with any button or none. Just change or delete if(Input.GetMouseButton(0)).

We need maximum and minimum values for the axes and assign sensitivities.

You can download source code here. Attach “CameraMovement” script to your camera.

©Coffee Break Codes – Move, Zoom and Rotate Camera – Unity3D (C#)

Leave a comment

Your email address will not be published. Required fields are marked *

100 thoughts on “Move, Zoom and Rotate Camera – Unity3D (C#)

      • sunarto ryan

        Thank you very much!!!!

        This tutorial was work in my Unity!
        This is C# and I like it too, it is simple code.
        I have try to find but can’t find any work but simple code. And finally I’ve found here. Thanks alot.!!!

  • Thomas

    How can I get this to work on a mobile device with touch? Can I get some help on adding that to this code. Otherwise, it works perfectly for me. Thanks!

  • valid22

    Look at this code I’ve used.

    using System;
    using UnityEngine;

    public class Camera1 : MonoBehaviour
    public GameObject Obj = null;
    public float minX = -360.0f;
    public float maxX = 360.0f;

    public float minY = -45.0f;
    public float maxY = 45.0f;

    public float sensX = 100.0f;
    public float sensY = 100.0f;

    float rotationY = 0.0f;
    float rotationX = 0.0f;

    float MouseX;
    float MouseY;

    void Update()
    var x = Input.GetAxis("Mouse X");
    var y = Input.GetAxis("Mouse Y");
    if (x != MouseX || y != MouseY)
    rotationX += x * sensX * Time.deltaTime;
    rotationY += y * sensY * Time.deltaTime;
    rotationY = Mathf.Clamp(rotationY, minY, maxY);
    MouseX = x;
    MouseY = y;
    Obj.transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);

    Where GameObject is your player. So you can use both mouse and key-buttons and play smoothly!

  • antonyhalfalai

    for code (script of move) version of unity 5,5
    void Update () {
    if (Input.GetKey (KeyCode.W)) { // al precionar la tecla.W))
    transform.Translate (new Vector3 (0, 0, 0.1f)); //cambiar posision.trasladar (aun nuevo vector(usando estas codenadas)
    } else {
    if (Input.GetKey (KeyCode.S)) {
    transform.Translate (new Vector3 (0, 0,-0.1f)); //cambiar posision.trasladar (aun nuevo vector(usando estas codenadas)
    if (Input.GetKey (KeyCode.D)) {
    transform.Translate (new Vector3 (0.1f, 0, 0)); //cambiar posision.trasladar (aun nuevo vector(usando estas codenadas)
    } else {
    if (Input.GetKey (KeyCode.A)) {
    transform.Translate (new Vector3 (-0.1f, 0, 0)); //cambiar posision.trasladar (aun nuevo vector(usando estas codenadas)

  • cholasimmons

    From now on I consider myself a Pro Unity Coder. lol
    The above code made the camera scroll up and down beside my object, then i tweaked it to this…

    transform.Translate(new Vector3(0,0,scroll * zoomSpeed));

    now it’s fine, just need to make it smooth. haha

  • p33587

    I’m really enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more pleasant for me to come here
    and visit more often. Did you hire out a designer to create your theme?
    Exceptional work!

  • targeted individuals

    A Targeted Individual is someone that has been selected by the Deep State (usually FBI or CIA) to unwillingly participate in a government experimental torture program. This program is designed to break down the individual and “neutralize the person,” using psychological, physical, and emotional stress. The ultimate goal of this program is to control the entire global population. Political activists and whistleblowers are two of the main targets. Family and spousal relationships are usually destroyed, as part of this torture.

  • targeted individuals

    A Targeted Individual is someone that has been selected by the Deep State (usually FBI or CIA) to unwillingly participate in a government experimental torture program. This program is designed to break down the individual and “neutralize the person,” using psychological, physical, and emotional stress. The ultimate goal of this program is to control the entire global population. Political activists and whistleblowers are two of the main targets. Family and spousal relationships are usually destroyed, as part of this torture.

  • Neuroweapons

    A Targeted Individual is someone that has been selected by the Deep State (usually FBI or CIA) to unwillingly participate in a government experimental torture program. This program is designed to break down the individual and “neutralize the person,” using psychological, physical, and emotional stress. The ultimate goal of this program is to control the entire global population. Political activists and whistleblowers are two of the main targets. Family and spousal relationships are usually destroyed, as part of this torture.

  • Alexander

    I’m in a band wallpaper paste recipes Like many southern cultures, we have a tradition of le stockfish, dried salted morue [cod] or églefin [haddock], reconstituted in a ragout like Portuguese bacalhau. In the winter there’s la daube, a Provençal stew of beef braised in wine with vegetables, garlic and herbs such as rosemary and even lavender.

  • Ashton

    A pension scheme 428i black wallpaper The Indian Women’s Press Club demanded authorities “provide a secure environment for women on a priority basis.” Journalists rallied in Indian cities from the south-coast metropolis of Chennai to Gauhati in northeast Assam state.

  • Salvador

    I’d like to send this to leopard wallpaper 1680 “Personal responsibility is seen as very important because it reveals how honest a person is and therefore how much we can trust them,” Krogman wrote. “There is a great deal of debate on the issue of how far a society should go in making sure that every person takes care of his/her personal responsibilities.”

  • Lyman

    I’m training to be an engineer top cars wallpaper The company didn’t mention how much the new glass would cost, only saying that it would be “1 to 2 percent of a notebook’s retail price,” but we can’t imagine laptop prices going up simply because of a change in the glass that manufacturers use.

  • Galen

    US dollars photoshot wallpaper “When you think about how many thousands of pages theDodd-Frank law is compared to this tiny provision and the amountof outcry and noise and hand-wringing and whining, this tellsyou just how important this provision is to investors and howdesperately companies want to do anything to not disclose it,”said Vineeta Anand, chief research analyst for the AFL-CIO’soffice of investment.

  • Arthur

    I’m at Liverpool University live nokia wallpaper North Korea trains young computer experts in hacking techniques at elite schools in the capital, Pyongyang. Star performers are selected for 10 years of training at Kim Il-sung Military University and other top colleges.

  • Sofia

    Could you transfer $1000 from my current account to my deposit account? fluorescent wallpapers for mobile “We urge all parties involved in the disappearance of Father Paolo to immediately come forward and release him,” the coalition said in a statement released in Istanbul on Saturday. It described the priest as a “wise man of peace and compassion” who engaged in interfaith dialogue with Muslims and forged close ties with people all over Syria.

  • Carson

    What’s your number? wallpaper that looks like distressed wood In his first State of the State speech, Gov. Cuomo recognized that youth justice is one of the civil rights issues of our time. Since then, he has successfully spearheaded the closure of underutilized upstate youth placement facilities, invested in effective alternatives to detention and incarceration and recognized that the youth justice system functions better when rehabilitative programs keep children closer to their homes and communities.

  • Kareem

    In tens, please (ten pound notes) eddie stobart wallpaper In response to Merck’s suspension of Zilmax, Tyson spokesmanGary Mickelson said: “We appreciate Merck’s decision and willcontinue to monitor this issue. We’ll also continue to seekinput from our Animal Well-Being Advisory Panel as well as otherindependent animal health and welfare experts.”

  • Simon

    Where are you from? cool car wallpapers hd 1080p However, the Center notes that only 24 percent of people said they were familiar with the term palliative care. If you are a loved one are diagnosed with a serious illness, ask your treating doctor if palliative care is available and request a palliative care consultation.

  • Infest

    When do you want me to start? murderdolls wallpaper Ryan Dunn has been permanently memorialized by a ‘Jackass’ co-star in the form of a tattoo. Jason (Wee-Man) Acuna revealed on Twitter that he had Dunn’s face inked on his right leg. Dunn, 34, died after he crashed his Porsche while driving drunk in West Goshen, Pa.

  • Dusty

    I came here to study registry wallpaperstyle 10 In the United States, BoA-ML is the largest bank in physical U.S. electricity trading. Areview of the bank’s sales, revealed in filings with FERC, showed it made over $11 billion intotal sales between 2009 and the third quarter of last year, and has been growing that business.

  • Mya

    In a meeting next purple stripe wallpaper Africa’s biggest oil producer after Nigeria, Angola hasposted rapid growth since the end of a long civil war in 2002but has been beset by criticism of its opaque finances andpervasive graft. Transparency International ranks Angola as the19th most corrupt country in its global index of 176 countries.

  • Ricky

    I like it a lot wallpapers from macbook Errol Morris’s “The Unknown Known,” essentially a series of interviews with former U.S. defense secretary Donald Rumsfeld, revisits his tumultuous five years at the Pentagon under President George W. Bush and his actions in building the case for the U.S. invasion of Iraq.

  • Lenny

    A staff restaurant tulip field desktop wallpaper None of the parties question whether Detroit is in deep trouble. More than one-third of the city’s residents live below the government poverty line. There are some 78,000 abandoned structures and just 40 percent of the street lights work. The population has shrunk to less than 700,000, from a peak of 1.8 million in 1950, and only 53 percent of property owners paid their 2011 property taxes.

  • Tomas

    Can you put it on the scales, please? dragon optical wallpaper The country’s new leaders have signalled they want to speedthe process of making the yuan fully convertible overthe next few years, as part of efforts to boost the currency’suse in trade and support wider financial reforms.

  • Derick

    I never went to university wallpaper paste recipes The picture of the receipt contained confidential information about Barnes, including his name, the last digits of his card number and his illegible signature. Barnes said he had to change his banking information and order a new debit card.

  • Thanh

    Where do you study? wallpaper undead nightmare Pouliot has dealt with plenty of “negative stuff” in his career, including not being selected until the 11th round (207th) of the 2002 OHL Priority Selection by the Sudbury Wolves. There, he played parts of three seasons with now-Rangers teammate Marc Staal, who captained the Wolves in Pouliot’s final junior season of 2006.

  • Buddy

    I’d like to open a personal account wallpaper shakugan no shana hd McDonald’s, which often bears the brunt of criticism over the restaurant industry’s penchant for tempting diners with indulgent and often high-calorie food, said it would offer the option in all of its 20 major global markets by 2020.

  • Bobber

    Another year snow wallpaper 1280 They noted that it has been suggested that kissing may allow people to subconsciously assess a potential partner through taste or smell, thus taking in biological cues for compatibility, genetic fitness or general health.

  • Nolan

    What line of work are you in? woven wallpaper uk I believe that what we are beginning to observe of undesired economic and social outcomes is less about system of systems artifacts than of the fundamental flaws of capitalism and the thousands of years old concepts of property ownership when these principles are allowed to play out at speed and scale.

  • Boyce

    Cool site goodluck 🙂 ubuntu wallpaper 60 The exports index moderated to 49.5 from 47.5, suggestingdemand from abroad remained weak even as the measure shrank lessthan in June. The imports index slowed to 50.5 from 53.5. (Reporting by Leah Schnurr; Editing by Meredith Mazzilli)

  • Efren

    Sorry, I’m busy at the moment wallpapers orquideas hd The Refco fraud, which was revealed soon after the company’s August 2005 initial public offering, led to the prosecution of several executives. Former chief executive Phillip Bennett is serving a 16-year prison sentence and former president Tone Grant is serving 10 years.

  • Nelson

    I’m afraid that number’s ex-directory wallpaper hd 1080p supernatural Automatic Renewal Program: Your subscription will continue without interruption for as long as you wish, unless you instruct us otherwise. Your subscription will automatically renew at the end of the term unless you authorize cancellation. Each year, you’ll receive a notice and you authorize that your credit/debit card will be charged the annual subscription rate(s). You may cancel at any time during your subscription and receive a full refund on all unsent issues. If your credit/debit card or other billing method can not be charged, we will bill you directly instead.

  • Adam

    How much were you paid in your last job? full hd iphone 6 wallpaper download “I’m trying to tread that fine line of being respectful as a guest in this country and also speaking against some serious injustices that I see,” he said. “As adamant as I am about this issue, I don’t know what me sitting in jail is good for.”

  • Antonio

    Could you tell me the dialing code for ? wallpapers orquideas hd When he spoke, Chris had the uncanny ability to express himself in kaleidoscopic terms, highlighting and analyzing each angle of the story before nimbly moving on to the next aspect — one you'd never quite formulated before. It was a quiet, bravura performance, and it was impressive as hell.

  • Keenan

    I sing in a choir jdm integra wallpapers Ritzer was reported missing at about 11:20 p.m. Tuesday when she did not return home and did not answer her cellphone. Police went to the high school, where they found blood in a second-floor bathroom, prompting a search of the grounds and the discovery of her body shortly before 3 a.m.

  • Faith

    Insufficient funds wallpapers wow mop In addition, I believe no federal judge is going to stop the arbitration from going forward or prevent evidence that was gathered by MLB investigators from being entered at the arbitration. Every player hit with a suspension related to the Biognesis Clinic investigation took his punishment, except for Rodriguez. We can assume it was because the evidence against each of them was overwhelming.

  • Randal

    Best Site Good Work pao wallpapers download The 5C, which comes in a range of bright colors, carries aprice tag of $549 for an unlocked 16 GB model in the UnitedStates, though Apple has a history of cutting iPhone prices oncea model has been on the market for a while, ISI’s Marshall said.

  • Rosendo

    I saw your advert in the paper wallpapered furniture diy “By repealing DADT, the country and the military have taken a significant step toward equality for all who want to serve their country in uniform. But there are other discriminatory policies in the military that the repeal of DADT does not change, including the medical regulatory ban in place for aspiring or current service members who identify as transgender,” it states.

  • Forest

    I’d like to send this letter by kustom wallpapers reddit All concerned have apologised profusely, of course, and the costumes are no longer available. Asda has made a £25,000 donation to mental health charity Mind; Tesco has grovelled. All concerned would rather we forgot about the entire affair. After all, “heartless” and “crass” are not words with which major retailers like to be associated.

  • Caden

    What’s the current interest rate for personal loans? best spring wallpapers for desktop “Now that we have ground proof and historical evidence,” she added, “my goal is to go to Egypt with a team of U.S. scientists and videographers to help validate the evidence found by the expedition team and to prove if these sites are lost pyramid complexes.”

  • Claud

    This site is crazy 🙂 wallpaper exo lockscreens A European-led group, also brokered by IndustriALL but separate from the compensation talks, is working on the same issue, but retailers signing up to its accord accept a binding arbitration process on safety issues, enforceable in the courts of the country where a company is domiciled.

  • Fermin

    I’m a partner in top gun wallpaper hd According to the rules, common equity Tier will only be composed of common stock and related surplus, and retained earnings, with deferred tax assets and mortgage servicing assets, and significant investments in the capital instruments of unconsolidated financial institutions being deducted.

  • Salvador

    Do you know each other? rihanna stay wallpaper This total of 42 for the Hundred Years War is attacks for which there is clear documentary evidence. Many more raids are mentioned in French and English archives, but with insufficient detail to include them in the total.

  • Ian

    Do you know the number for ? windows stretch wallpaper dual monitor Saudi Arabia, which is also campaigning to be elected to the U.N. Human Rights Council, grants fathers guardianship over their daughters, giving them control over who they can marry and when, and it is also the only country in the world where women are barred from driving.

  • Randy

    How do I get an outside line? wallpapered furniture diy “New Yorkers work hard,” Quinn told the Daily News. “They have a right to come home, sit on their couches and watch whatever they want. These are two corporate entities that can’t get out of their own way. It is not acceptable.”

  • Raphael

    I’ll put her on aqua metallic wallpaper Inside the Broadhurst Theater, the entire cast had been on the stage after the matinee, doing a Q&A with audience members. Gaston, Mastrogiorgio and Peter Gerety were there. So was Peter Scolari, who played Michael Daly, and Courtney Vance, who won a Tony for his performance as the late editor Hap Hairston; and Christopher McDonald, a streak of verbal light as lawyer Eddie Hayes.

  • Jordon

    I have my own business best spring wallpapers for desktop His ambition for quality is high. I’d expected the aim to be an £8-ish wine that would actually sell for £10-£12 (think of the uplift offered by scarcity value). But Monery says the intention is to produce wine that can sell for £15 a bottle, which is another matter altogether.

  • Andrew

    I love this site joanna aimee wallpaper GM spokesman Alan Adler said safety is a priority for the company. “The recalls are indicative of our dedication to making sure that problems that are spotted are fixed and customers can have complete confidence and peace of mind in driving,” he said.

  • Barbera

    Your account’s overdrawn family guy live wallpapers android If earnings reach DiNapoli’s projection for this year, thatwill top the $13.4 billion forecast in the city’s four-yearfinancial plan, even while falling from 2012, according to thereport. DiNapoli said he expects the industry will continue tostreamline as it adapts to changes in regulation and markets.

  • Jasper

    Do you need a work permit? scarlet witch wallpaper download About 78 million U.S. adults are considered obese. Themajority — more than 50 million — are non-Hispanic white,according to the report from the National Center for HealthStatistics, part of the U.S. Centers of Disease Control andPrevention.

  • Jaime

    Did you go to university? cute real baby panda wallpaper It was proper hard work. We did 11-hour shifts. It was the best job I’ve ever done, but I was a volunteer – we weren’t getting paid. Part of the pleasure was that different set of values the work represented. There is more to fulfilment and achievement than financial gain. Volunteering may not pay in cash, but it pays in emotion, passion and drive. It pays to see the difference you’ve made, and making friends along the way is always a bonus.

  • Juan

    I’m interested in this position child models bbs One of the systems that is operating without a current license, known as iPost, was given an award two years ago for “significantly improving the effectiveness of the nation’s cyber security.”  According to the inspector general’s report, auditors couldn’t find any documentation to back up how the award-winning system was created or maintained, nor any source code for the information it was supposed to track.

  • Ricardo

    I work here preteez toplist The WGS network is used to relay television broadcasts, video conferences, images and other high-bandwidth data to and from ships, aircraft, ground forces, operations centers, the U.S. Department of State, the White House and select partners worldwide.

  • Sanford

    I read a lot nn lollita But shares in RSM Tenon, which has offices in Aberdeen, Edinburgh and Glasgow and is recovering after a torrid 2012, plunged on the announcement after it also said that its hefty debt pile meant any potential transaction would require the support of its sole lender, Lloyds.

  • Ashley

    Have you got any qualifications? nizagara gold 120 review NOTES: RW Cal Clutterbuck played his first game with the Islanders. He was acquired in an offseason trade from Minnesota, then sat out the first three games this season with a leg laceration. . Khabibulin was Chicago’s No. 1 goaltender for four seasons, from 2005-09. . The 21-year-old Nordstrom played in his fourth NHL game. . Both teams play again on Saturday night. The Blackhawks host Buffalo and the Islanders are at Nashville.

  • Modesto

    There’s a three month trial period underage pussy This week, researchers at Carnegie Mellon University released a smartphone app called SafeSlinger they say encrypts text messages so they cannot be read by cell carriers, Internet providers, employers “or anyone else.”

  • Frances

    Could you send me an application form? super nizagara forte In addition, the strong expansion of renewables has hurt theprofitability of gas plants, as power from solar and windsources takes priority in being fed into the electricity grid,reducing the hours gas plants can run.

  • Brandon

    How many are there in a book? lolas getting fucked hard By Monday, at least 70 out of 271 members of the Constituent Assembly withdrew from the body, according to local media. A sit-in outside the assembly building continued for a third day, and demonstrators called for a “national rescue government” and accused the Islamist leaders of lying to people in the name of religion.

  • Blake

    I’m doing a masters in law kgn wallpaper full hd It might sound exciting and a little bit tempting but it’s good to consider the long term effects of tattooing your lovers name on your body. The tattoo will be there forever, will he or she? There are many people out there who have regretted getting a past love’s name tattooed on their body.

  • Robin

    Whereabouts are you from? valya pthc That 2011 extension is called a “delivery order” rather thana contract because it fell under the original 2007 agreement forCGI Federal to provide IT services to the Centers for Medicare &Medicaid Services, the lead Obamacare agency. CGI Federalreported at the time of the extension that it had received $55.7million for the first year’s work to build

  • Anton

    Have you seen any good films recently? al4a videos The U.S. government’s monthly jobs report due out at the endof the week was also keeping investors on edge, particularlybecause the Fed has made the unemployment rate a pillar in itsdecision on economic stimulus.

  • Friend35

    Could you please repeat that? nizagara 100 dosage There is a recognition inside and outside of the White House that the president could eventually catch some of the public anger from a prolonged shutdown, especially if the U.S. economy takes a hit from the idling of hundreds of thousands of government workers.

  • Cleveland

    A packet of envelopes al4a videos Earlier, Djokovic looked a little weary in the opening three games after a long-haul flight from New York following his U.S. Open final defeat by Rafael Nadal but it was one-way traffic once he found his feet against Pospisil.

  • Lynwood

    Could I take your name and number, please? yuvutu videos Public worker contracts are often protected by law against attempts to cut costs. That’s a common link between Detroit, the California cities of Stockton and San Bernardino which filed for bankruptcy in 2012, and other local governments across the United States.

  • Abigail

    I stay at home and look after the children al4a tube Swedish biometric component maker Fingerprint Cards AB, for example, has seen its share price rise 1,400 percent in the past year. The company predicts the industry will ship up to 100 million consumer electronic devices embedded with fingerprint scanners this year, rising to more than 1 billion in 2015 as biometrics finds its way into TV remotes, gaming consoles and cameras.

  • Cortez

    Yes, I play the guitar yuvutu tube All in all, a ticket to Mars doesn’t sound so bad, as long as you’re capable of suppressing your inner foodie and subsisting off processed delicacies like freeze-dried meat and dehydrated fruit pieces. Here, in no special order, are a few of the better-sounding things the participants were able to eat:

  • Bruce

    I’d like to open an account yuvutu tube Patients taking alirocumab started out with a low 75-milligram dose every two weeks, but this was increased to 150 milligrams at week 12 if their LDL levels at week eight were above 70. Most patients, however, remained on the low dose throughout the study because they got their LDL levels below that threshold – an aggressive LDL target – by the eighth week.

  • Vernon

    We work together al4a mobile
    Polling stations opened at 8 a.m. (0600 GMT) and the firstexit polls were to be published at 6 p.m. (1600 GMT). Of the 62million Germans eligible to vote, about a third describedthemselves in the run-up to the election as undecided, adding tothe uncertainty.

  • Ellsworth

    I sing in a choir wallpaper japan As is typical with Wikipedians, a response emerged from a mixture of cordial discussions, tedious arguments, and online wrestling matches—but it was sophisticated. The project’s most active volunteers introduced a raft of new editing tools and bureaucratic procedures intended to combat the bad edits. They created software that allowed fellow editors to quickly survey recent changes and reject them or admonish their authors with a single mouse click. They set loose automated “bots” that could reverse any incorrectly formatted changes or those that were likely to be vandalism and dispatch warning messages to the offending editors.

  • Guadalupe

    How much were you paid in your last job? al4a mobile
    A number of senators – mostly Democrats – have criticized Summers for easing banking restrictions and not regulating derivatives when he was treasury secretary in the 1990s during the presidency of Bill Clinton.