I am trying to get my player+camera to follow my mouse cursor at a distance in a top down view game…
here is the game project demo: http://kuroato.com/ghostwarrior/
I was able to get the player model to follow the mouse, but the camera does not move or follow the player…
I am using a script i came across via Google called SmoothFollow2D.js, any tips to get this working properly?
var target : Transform;
var smoothTime = 0.3;
var xOffset : float = 1.0;
var yOffset : float = 1.0;
private var thisTransform : Transform;
private var velocity : Vector2;
function Start()
{
thisTransform = transform;
}
function LateUpdate()
{
thisTransform.position.x = Mathf.Lerp( thisTransform.position.x, target.position.x + xOffset, Time.deltaTime * smoothTime);
thisTransform.position.y = Mathf.Lerp( thisTransform.position.y, target.position.y + yOffset, Time.deltaTime * smoothTime);
}
Using a character controller would probably be better than translating your object.
Start here:
This is a basic character controller script. But it will need to be changed some to achieve what you are going after.
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = -Physics.gravity.y * 2;
var cameraDistance : float = 10;
private var moveDirection : Vector3 = Vector3.zero;
function Update() {
var controller : CharacterController = gameObject.GetComponent(CharacterController);
if(!CharacterController) controller = gameObject.AddComponent(CharacterController);
// setup a plane, ray and collector for a raycast.
var plane:Plane = new Plane(transform.up, transform.position);
var ray:Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var dist:float;
// raycast the plane and collect the collector
// this should always go off
if(plane.Raycast(ray, dist)){
// make your player LookAt the point.
transform.LookAt(ray.GetPoint(dist));
}
if (controller.isGrounded) {
// get the inputs
moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// transform them into a direction based on the direction of the player.
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
// set the camera to the palyers current position and move it up a distance.
Camera.main.transform.position = transform.position + Vector3.up * cameraDistance;
// just in case, make it look at the player.
Camera.main.transform.LookAt(transform);
}
Read over it, understand it, test it and see if you have any questions.
1 Like