IamdevelopingtheUnitytrainingdaygame(Nightmares)throughtutorialsandrealizedthattheplayerdidnotrecognizecollisionsintheobjects.
Whenyouaddthe"Capsule Collider" component, the bug has been fixed, but the character moves on its own. Where is the error?
usingUnityEngine;publicclassPlayerMovement:MonoBehaviour{publicfloatspeed=6f;Vector3movement;Animatoranim;RigidbodyplayerRigidbody;intfloorMask;floatcamRayLenght=100f;voidAwake(){floorMask=LayerMask.GetMask("Floor");
anim = GetComponent <Animator> ();
playerRigidbody = GetComponent <Rigidbody> ();
}
void Update ()
{
float h =Input.GetAxisRaw("Horizontal");
float v =Input.GetAxisRaw("Vertical");
Move (h,v);
Turning ();
Animating (h, v);
}
void Move (float h, float v)
{
movement.Set (h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime ;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning ()
{
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if(Physics.Raycast (camRay, out floorHit, camRayLenght, floorMask))
{
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
void Animating (float h,float v)
{
bool walking = h != 0f || v !=0f;
anim.SetBool ("IsWalking", walking);
}
}