6 Replies - 4331 Views - Last Post: 16 March 2014 - 06:09 PM Rate Topic: -----

#1 TrewSx  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 50
  • Joined: 07-June 12

Click to Move + Character Controller in Unity/javascript

Posted 22 February 2013 - 06:36 AM

Hello there,

i am working on RPG style game and for the movement i would like to use either click to move and WASD buttons on keyboard.
If i use this script it all works fine for click to move, but i cannot use the unity character controller component. My capsule suddenly starts falling through my Plane/Cube. I want to use either keyboard or mouse, so far i got mouse and keyboard working separately but not both at the same time. Pls help

//Click to Move script
//Moves the object towards the mouse position on left mouse click

var smooth : int; //Determines how quickly object moves towards the position

private var targetPosition : Vector3; //Current target position


function FixedUpdate () {
	if(Input.GetKeyDown(KeyCode.Mouse0) || Input.GetKey(KeyCode.Mouse0)) {
		var playerPlane = new Plane(Vector3.up, transform.position);
		var ray			= Camera.main.ScreenPointToRay (Input.mousePosition);
		var hitdist		= 0.0;
		
		if(playerPlane.Raycast (ray, hitdist)) {
			var targetPoint    = ray.GetPoint(hitdist);
			targetPosition     = ray.GetPoint(hitdist);
			var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
			transform.rotation = targetRotation;
			}
	}
			transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * smooth);

}


FPSControler
 var forwardSpeed = 10; 
 var backwardSpeed = 5; 
 var strafeSpeed = 8; 
 
 function FixedUpdate () { 
    // Step1: Get your input values 
    horizontal = Input.GetAxis("Horizontal"); 
    vertical = Input.GetAxis("Vertical"); 
    // Step 2: Limit the movement on angles and then multiply those results 
    // by their appropriate speed variables 
    percentofpercent = Mathf.Abs(horizontal) + Mathf.Abs(vertical) - 1.0; 
    if (percentofpercent > 0.1) { 
       // if we're here, then we're not moving in a straight line 
       // my math here might be kinda confusing and sloppy...so don't look! 
       percentofpercent = percentofpercent * 10000; 
       percentofpercent = Mathf.Sqrt(percentofpercent); 
       percentofpercent = percentofpercent / 100; 
       finalMultiplier = percentofpercent * .25; 
       horizontal = horizontal - (horizontal * finalMultiplier); 
       vertical = vertical - (vertical * finalMultiplier); 
    } 
    if (vertical > 0) { 
       vertical = vertical * forwardSpeed; 
    } 
    if (vertical < 0) { 
       vertical = vertical * backwardSpeed; 
    } 
    horizontal = horizontal * strafeSpeed; 
    // Step 3: Derive a vector on which to travel, based on the combined 
    // influence of BOTH axes 
    tubeFinalVector = transform.TransformDirection (Vector3(horizontal,0,vertical)); 
    // Step 4: Apply the final movement in world space 
    rigidbody.velocity.z = tubeFinalVector.z; 
    rigidbody.velocity.x = tubeFinalVector.x; 
 } 
 function Awake () { 
    rigidbody.freezeRotation = true; 
 }


Is This A Good Question/Topic? 0
  • +

Replies To: Click to Move + Character Controller in Unity/javascript

#2 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Click to Move + Character Controller in Unity/javascript

Posted 22 February 2013 - 12:28 PM

Put code in that stops your capsule moving vertically. :)
Was This Post Helpful? 1
  • +
  • -

#3 TrewSx  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 50
  • Joined: 07-June 12

Re: Click to Move + Character Controller in Unity/javascript

Posted 23 February 2013 - 09:35 AM

ok, i will try that, thank you
Was This Post Helpful? 0
  • +
  • -

#4 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Click to Move + Character Controller in Unity/javascript

Posted 23 February 2013 - 09:44 AM

No problem.
Was This Post Helpful? 0
  • +
  • -

#5 maXXen888  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 25-February 14

Re: Click to Move + Character Controller in Unity/javascript

Posted 25 February 2014 - 03:47 AM

hi. i am really new to coding so i tried to use your code. but all i could do was spin it. not move it. is there any change. ANY CHANGE AT ALL that you did to the code when you uploaded it. Thanks in advance. i wont use this in any way with money involved. :innocent:
Was This Post Helpful? 0
  • +
  • -

#6 AdoTheLimey  Icon User is offline

  • D.I.C Head

Reputation: 19
  • View blog
  • Posts: 78
  • Joined: 28-June 10

Re: Click to Move + Character Controller in Unity/javascript

Posted 16 March 2014 - 02:22 PM

The character controller includes a rigidbody, so you need to add a Collider to whatever object you are using as Terrain.
Was This Post Helpful? 1
  • +
  • -

#7 BBeck  Icon User is offline

  • Here to help.
  • member icon


Reputation: 574
  • View blog
  • Posts: 1,279
  • Joined: 24-April 12

Re: Click to Move + Character Controller in Unity/javascript

Posted 16 March 2014 - 06:09 PM

The player game object needs the Character Controller component setup. And the ground needs some sort of collision detection. If you're using a terrain, it should be included and shouldn't be a problem. Other surfaces may require adding a collider. For example, if you setup a box as the "ground" you may have to add a collider to it.

Be aware that you probably should place your character just slightly above the ground and let them fall to the ground when the game starts; if they start even slightly below the ground, they may fall right through it.

Here's my C# code for the first person camera. I move the main camera to be a child of the character and attach this script to the camera.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
{
	private Transform CameraTransform = null;
	private Vector3 CamerasForwardVector;
	private float CameraElevation = 1.8f;
	private const float MinCameraDistance = 0.5f;
	private const float MaxCameraDistance = 3f;
	private const float MinCameraHeight = 0.3f;
	private const float MaxCameraHeight = 4f;
	private const float ThirdPersonCameraTurnSpeed = 2f;
	protected enum CameraModes {FirstPerson, ThirdPerson};
	private CameraModes CameraMode = CameraModes.ThirdPerson;
	private Transform FirstPersonCameraTransformSave = null;
	private Transform ThirdPersonCameraTransformSave = null;
	private float HeadYaw = 0f;
	private const float HeadYawRate = 0.05f;
	private const float MaxHeadYaw = 75f;
	private float HeadPitch = 0f;
	private const float HeadPitchRate = 0.05f;
	private const float MaxHeadPitch = 48f;
	public const float EyeHeight = 1.68f;	//1.68m is an average man.
	private GameObject CrossHairsTexture = null;	
	

	// Use this for initialization
	void Start () 
	{
		CameraTransform = transform;
		CameraTransform.LookAt(CameraTransform.parent.localPosition+Vector3.up * EyeHeight, Vector3.up);
		CrossHairsTexture = GameObject.Find ("CrossHairs");
	}

	void Update()
	{

	}


	// Update is called once per frame
	void LateUpdate () 
	{
		//if(!CameraTransform && Camera.main) CameraTransform = Camera.main.transform;
		//if(!CameraTransform) Debug.Log("Please assign a camera to the CameraController script.");

		if (!CameraTransform) Debug.Log ("Please assign the CameraController script to a Camera object.");
		else 
		{
			
			if (Input.GetButtonDown ("RightThumbStickButton"))
			{
				if (CameraMode == CameraModes.ThirdPerson)
				{
					CameraMode = CameraModes.FirstPerson;
					ThirdPersonCameraTransformSave = CameraTransform;
			
					CrossHairsTexture.guiTexture.enabled = true;
/*					CameraTransform.localPosition = new Vector3(0f,EyeHeight,0.035f);	//Offset because model is not zero'ed on the Z axis.
					CameraTransform.localRotation = Quaternion.identity;
*/				}
				else
				{ 
					CameraMode = CameraModes.ThirdPerson;
					FirstPersonCameraTransformSave = CameraTransform;
				//		CameraTransform = ThirdPersonCameraTransformSave;
					CameraElevation = EyeHeight + 0.1f;
					CameraTransform.localPosition = new Vector3(0f, CameraElevation, -1.5f);	//Offset because model is not zero'ed on the Z axis.

					CrossHairsTexture.guiTexture.enabled = false;
					//CameraTransform.localRotation = Quaternion.identity * Quaternion.AngleAxis(0f, Vector3.up);

				}
			}
			

			if (CameraMode == CameraModes.FirstPerson)
			{
				ControlFirstPersonCamera();		
				//EvasMesh.enabled = false;
			}
			else
			{
				//EvasMesh.enabled = true;
				ControlThirdPersonCamera();
	
			}
		}
	}


	void ControlFirstPersonCamera()
	{
		float RightThumbHoriz = Input.GetAxis ("RightThumbHorizontal");
		float RightThumbVert = Input.GetAxis ("RightThumbVertical");
		float HorizontalDirection = Mathf.Sign (RightThumbHoriz);
		float VerticalDirection = Mathf.Sign (RightThumbVert);

/*		
		if (Input.GetButton("Fire4")) 
		{
			CameraTransform.localPosition = new Vector3(0f,EyeHeight-0.2f,0.9f);
			
		}
			else CameraTransform.localPosition = new Vector3(0f,EyeHeight,0.025f);	*/

		CameraTransform.localPosition = new Vector3(0f,EyeHeight,0.025f);	
		CameraTransform.localRotation = Quaternion.identity;		
		if (RightThumbHoriz != 0f)
		{
			HeadYaw += HeadYawRate * HorizontalDirection ;
			if (HorizontalDirection > 0 && HeadYaw > RightThumbHoriz) HeadYaw = RightThumbHoriz;
			if (HorizontalDirection < 0 && HeadYaw < RightThumbHoriz) HeadYaw = RightThumbHoriz;
			CameraTransform.RotateAround (CameraTransform.position, Vector3.up, MaxHeadYaw * HeadYaw);
		}
		else
		{
			if (HeadYaw > 0.05)
			{
				HeadYaw -= HeadYawRate;
				CameraTransform.RotateAround (CameraTransform.position, Vector3.up, MaxHeadYaw * HeadYaw);
			}
			else if (HeadYaw < -0.05) 
			{
				HeadYaw += HeadYawRate;
				CameraTransform.RotateAround (CameraTransform.position, Vector3.up, MaxHeadYaw * HeadYaw);
			}
			else HeadYaw = 0f;

			
		}

		if (RightThumbVert !=0)
		{
			HeadPitch += HeadPitchRate * VerticalDirection;
			if (VerticalDirection > 0 && HeadPitch > RightThumbVert) HeadPitch = RightThumbVert;
			if (VerticalDirection < 0 && HeadPitch < RightThumbVert) HeadPitch = RightThumbVert;
			
			CameraTransform.RotateAround (CameraTransform.position, CameraTransform.right, MaxHeadPitch * HeadPitch);
		}
		else
		{
			if (HeadPitch > 0.05)
			{
				HeadPitch -= HeadPitchRate;
				CameraTransform.RotateAround (CameraTransform.position, CameraTransform.right, MaxHeadPitch * HeadPitch);
			}
			else if (HeadPitch < -0.05) 
			{
				HeadPitch += HeadPitchRate;
				CameraTransform.RotateAround (CameraTransform.position, CameraTransform.right, MaxHeadPitch * HeadPitch);
			}
			else HeadPitch = 0f;
		}
	}

	
	void ControlThirdPersonCamera()
	{
		float RightThumbHoriz = Input.GetAxis ("RightThumbHorizontal");
		float RightThumbVert = Input.GetAxis ("RightThumbVertical");
		Vector2 XZPlaneCameraPosition;
		bool CameraPositionchanged = false;
		float TurnAngle;


		XZPlaneCameraPosition = new Vector2(CameraTransform.localPosition.x, CameraTransform.localPosition.z);		
		//Get a normalized 2D camera's forward vector in 3D.
		//CamerasForwardVector = CameraTransform.TransformDirection (Vector3.forward);
		
		//CamerasForwardVector.y = 0;
		
		//Rotate Camera	
		if (RightThumbHoriz != 0f)
		{
			TurnAngle = -RightThumbHoriz * ThirdPersonCameraTurnSpeed * Time.deltaTime;
			//CameraTransform.RotateAround (CameraTransform.parent.position, Vector3.up, 90f * Time.deltaTime * RightThumbHoriz);
			XZPlaneCameraPosition.x = XZPlaneCameraPosition.x * Mathf.Cos(TurnAngle) - XZPlaneCameraPosition.y * Mathf.Sin(TurnAngle);
			XZPlaneCameraPosition.y = XZPlaneCameraPosition.x * Mathf.Sin(TurnAngle) + XZPlaneCameraPosition.y * Mathf.Cos(TurnAngle);
			CameraPositionchanged = true;
		}
		
		//Hoist Camera
		if (RightThumbVert != 0) 
		{
			//CameraElevation += 0.75f * RightThumbVert * Time.deltaTime;
			CameraElevation = CameraTransform.localPosition.y + 0.75f * RightThumbVert * Time.deltaTime;
			
			CameraPositionchanged = true;
		}
		
		//Zoom Camera
		if (Input.GetKey (KeyCode.PageDown)) 
		{
			//CamerasForwardVector = CameraTransform.forward;
			//CamerasForwardVector = CamerasForwardVector.normalized;
			//CameraTransform.position += -CamerasForwardVector * Time.deltaTime;
			XZPlaneCameraPosition *= (1f + (Time.deltaTime * 2f));			

			//XZPlaneCameraPosition = new Vector2(CameraTransform.localPosition.x, CameraTransform.localPosition.z);

			if (XZPlaneCameraPosition.magnitude > MaxCameraDistance)
			{
				XZPlaneCameraPosition.Normalize ();
				XZPlaneCameraPosition *= MaxCameraDistance;
				/*CameraTransform.localPosition = new Vector3(XZPlaneCameraPosition.x, CameraElevation, XZPlaneCameraPosition.y);
				CameraTransform.LookAt(CameraTransform.parent.localPosition+Vector3.up * EyeHeight, Vector3.up);*/
				CameraElevation = CameraTransform.localPosition.y;
			}
			CameraPositionchanged = true;

			/*			CamerasForwardVector = CameraTransform.forward;
			CamerasForwardVector = CamerasForwardVector.normalized;
			CameraTransform.position += -CamerasForwardVector * Time.deltaTime * 1f * RightThumbVert;
			
			XZPlaneCameraPosition = new Vector2(CameraTransform.localPosition.x, CameraTransform.localPosition.z);
			if (XZPlaneCameraPosition.magnitude < MinCameraDistance)
			{
				XZPlaneCameraPosition.Normalize ();
				XZPlaneCameraPosition *= MinCameraDistance;
				CameraTransform.localPosition = new Vector3(XZPlaneCameraPosition.x, CameraElevation, XZPlaneCameraPosition.y);
				CameraTransform.LookAt(CameraTransform.parent.position+Vector3.up * 1.68f, Vector3.up);
			}
*/
		}
		if (Input.GetKey (KeyCode.PageUp)) 
		{
			//CamerasForwardVector = CameraTransform.forward;
			//CamerasForwardVector = CamerasForwardVector.normalized;
			//CameraTransform.position -= -CamerasForwardVector * Time.deltaTime;
			XZPlaneCameraPosition *= (1f - (Time.deltaTime * 2f));			

			if (XZPlaneCameraPosition.magnitude < MinCameraDistance)
			{
				XZPlaneCameraPosition.Normalize ();
				XZPlaneCameraPosition *= MinCameraDistance;
				/*CameraTransform.localPosition = new Vector3(XZPlaneCameraPosition.x, CameraElevation, XZPlaneCameraPosition.y);
				CameraTransform.LookAt(CameraTransform.parent.localPosition+Vector3.up * EyeHeight, Vector3.up);*/
				CameraElevation = CameraTransform.localPosition.y;
			}
			CameraPositionchanged = true;			
		}

		if (CameraPositionchanged)
		{
			if (CameraElevation > MaxCameraHeight) CameraElevation = MaxCameraHeight;
			else if (CameraElevation < MinCameraHeight) CameraElevation = MinCameraHeight;
			
			CameraTransform.localPosition = new Vector3(XZPlaneCameraPosition.x, CameraElevation, XZPlaneCameraPosition.y);
			//CameraTransform.localPosition = new Vector3(CameraTransform.localPosition.x, CameraElevation, CameraTransform.localPosition.z);
			CameraTransform.LookAt(CameraTransform.parent.localPosition+Vector3.up * EyeHeight, Vector3.up);
			
		}
		
	}


}



This post has been edited by BBeck: 16 March 2014 - 06:13 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1