x


C#, Dynamic Camera Speed based on Mouse Position

Basically I want to use the distance the mouse is to the center of the screen, to determine the speed of the cameras movments. This will allow the player to slowly move the camera if its close to their screen center, and quickly as the player is closer to the edges.

I was able to get the camera moving at a certain speed depending on position on the screen, but as soon as I attempt to dynamic based on distance away from screen center it tells me that the Vector 3 cannot be multiplied ('*') by a variable. What do I have to do to fix this?

Here is my prototype camera code:

using UnityEngine;

public class SmoothFollowCamera : MonoBehaviour {

//Static Camera Speed
public int CameraSpeedAcross = 10;

void Update () {

    var translation = Vector3.zero;
    //Identifies Screen Center
    var ScreenCenterWidth = (Screen.width * .5);
    //Dynamic Cammera Speed
    var CameraMovementAcross = (ScreenCenterWidth - Input.mousePosition.x);

    if (Input.mousePosition.x > ScreenCenterWidth)
    {
       translation += Vector3.right * -CameraMovementAcross * Time.deltaTime ;
    }
    if (Input.mousePosition.x < ScreenCenterWidth)
    {
       translation += Vector3.right * CameraSpeedAcross * Time.deltaTime;
    }
    camera.transform.position += translation;
more ▼

asked Aug 06 '11 at 06:55 PM

Methlodis gravatar image

Methlodis
1 1 1 2

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The problem you experience with being unable to multiply comes from using a "var" type variable definition. If you change that to a "float" you would be able to do it, you do however need to cast ScreenCenterWidth to a float to.

float CameraMovementAcross = ((float)ScreenCenterWidth - Input.mousePosition.x);

Hope it helps. :)

I actually recommend you use the respected variable types when defining variables. This will make it easier for you as you will have a better control over the types. ;)

more ▼

answered Aug 06 '11 at 07:23 PM

PaxNemesis gravatar image

PaxNemesis
235 9 11 21

Unfortunately it is now giving me a bug saying that I cannot 'implicitly convert type 'double to 'float'.

Is there something wrong with how I set-up the code,

Or will I have to rewrite most of it to get into a better logical format?

Aug 06 '11 at 07:38 PM Methlodis

when using float you have to put a "f" behind the number you are assigning: ".5f"

Aug 06 '11 at 07:50 PM PaxNemesis
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4163
x3004
x69
x11

asked: Aug 06 '11 at 06:55 PM

Seen: 966 times

Last Updated: Aug 06 '11 at 07:50 PM