- Home /
Colliding for my character
I've made that code for my character, I can not add any colliding to it with other objects. Rigidbody wont effect it by it's default. Can anyone help me out?
The script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class char_movement : MonoBehaviour
{
public float moveSpeed = 15.0f;
public float turnSpeed = 45.0f;
public bool built = false;
public float grove = 8.0f;
public float velo = 1.0f;
public float jumpStr = 10.0f;
public bool onjump = false;
public float timer = 1.0f;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
transform.position -= transform.TransformDirection(0,1.0f,0) * grove * velo * Time.deltaTime;
if(Physics.Raycast(transform.position,-Vector3.up,1f))
{
built=true;
Animateable();
}
else
{
built=false;
animation.Play("jump");
}
if(onjump)
{
timer-= 3.0f * Time.deltaTime;
transform.position+=transform.TransformDirection(0,2.0f,0)*jumpStr*Time.deltaTime;
jumpStr-=0.7f;
if(timer<=0.0)
{
onjump=false;
timer=1.0f;
jumpStr=10.0f;
}
}
if(built)
{
velo = 0.0f;
if(Input.GetButtonDown("Jump"))
{
onjump=true;
}
}
if(Input.GetKey(KeyCode.W))
transform.position += transform.TransformDirection(0,0,1.0f) * moveSpeed * Time.deltaTime;
if(Input.GetKey(KeyCode.S))
transform.position += -transform.TransformDirection(0,0,1.0f) * (moveSpeed-10.0f) * Time.deltaTime;
if(Input.GetKey(KeyCode.A))
transform.Rotate(Vector3.up * -turnSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.D))
transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
if(!built)
velo += 1.0f * Time.deltaTime;
}
//-------------------
void Animateable()
{
if(Input.GetKey(KeyCode.W))
{
animation.Play("walk");
}
else if(Input.GetKey(KeyCode.S))
{
animation.Play("walkback");
}
else if(Input.GetKey(KeyCode.A))
{
animation.Play("walk");
}
else if(Input.GetKey(KeyCode.D))
{
animation.Play("walk");
}
else
{
animation.Play("idle");
}
}
//--------------------
}
Comment
Answer by aldonaletto · Jul 21, 2011 at 02:12 PM
For Character Controllers you must use OnControllerColliderHit - but it reports collisions with the ground all the time, so you may want to filter out these collisions. A simple way is to ignore collisions with normals > 45 degrees:
void OnControllerColliderHit(ControllerColliderHit hit){
if (hit.normal.y < 0.707f) { // ignore collisions at the bottom
// do whatever you want
}
}
Answer by benk0913 · Jul 21, 2011 at 03:23 PM
Many thanks, i'll try it out and report back if it worked!