- Home /
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;
Answer by PaxNemesis · Aug 06, 2011 at 07:23 PM
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. ;)
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?
when using float you have to put a "f" behind the number you are assigning: ".5f"
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
2D camera zoom smoothing and limitations? 1 Answer
Camera follow an object within a circle? 1 Answer
Distribute terrain in zones 3 Answers
I need some help with camera rotations 0 Answers