- Home /
my character is going through walls and other objects
i have have used a character from Mixamo with animations and for the movement i have used transform.translate which is making the object move but my object is moving through walls and other objects. My code is here .. help me out that how can i bring in collisions.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class galcontrols : MonoBehaviour { static Animator anim; public float speed = 10F; public float rotationSpeed = 100.0F;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
float translation = Input.GetAxis("Vertical") * speed;
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
transform.Translate(0, 0, translation);
transform.Rotate(0, rotation, 0);
if(Input.GetButtonDown("Jump"))
{
anim.SetTrigger("isJumping");
}
if(translation!=0)
{
anim.SetBool("isRunning",true);
anim.SetBool("idle", false);
}
else
{
anim.SetBool("isRunning", false);
anim.SetBool("idle", true);
}
}
}
Answer by aditya · May 02, 2017 at 06:49 AM
To make physics effect your gameobjects you need to use rigidbody and if your are moving a gameobject with rigidbody attached you need to use MovePosition method of rigidbody class ... Attach a rigidbody to your character (if not already attached) and then take reference of this rigidbody in your code and move it using MovePosition
public Rigidbody char_RB;
void FixedUpdate(){
if(Input.GetAxis("Vertical")){
char_RB.MovePosition(char_RB.gameObject.transform.forward * speed);
}
}
Important : Always use FixedUpdate whenever dealing with physics
One addition to this answer, also use a Collider component on your gameObject. The combination of Rigidbody and a collider component (such as CapsuleCollider) should get your gameObject to react to Physics. If you want to avoid going through walls etc., you also have to make sure that the collider on your Character has "isTrigger" set to false. And you also have to add Collider Components to the walls, although you do not need to add a Rigidbody to the walls, since they are static objects and should not be moved by the Unity engine.
$$anonymous$$ovePosition does consider the physics engine. but it assigns the position like a teleport effect. so it will move things inside another collider. in his case it would probobly cause a bounce back or shake when pressing against another collider. for general smooth movement he pry wants to apply velocity ins$$anonymous$$d like this:
gameObject.rigidbody.velocity=new Vector3(0, 0, translation);
Answer by infinuscerro · Mar 08, 2019 at 02:13 PM
@kalti_mar I have same problem, the object through wall/object/cube. The problem solved after I reinstall the Unity software.