- Home /
Question by
Ottoz_H501 · Jul 10, 2020 at 07:10 PM ·
collisionmovementtransformmovement scripttransform.position
Character Transform shifting after colliding with objects
Hi! I'm having some troubles with basic movement of my character when it collides with objects, it seems like the Transform is getting shifted by the force applied by the collision.
Before the collision transform is in position:
After collision Transform is shifted:
My character has Capsule Collider and Rigidbody with Interpolate and Collision Detection Continuous Dynamic. Objects have Mesh colliders without IsTrigger.
I'm using following scripts for movement:
using UnityEngine;
public class InputHandler : MonoBehaviour
{
public Vector2 InputVector { get; private set; }
private void Update()
{
var h = Input.GetAxis("Horizontal");
var v = Input.GetAxis("Vertical");
InputVector = new Vector2(h, v);
}
}
And
using System;
using UnityEngine;
public class CharacterMover : MonoBehaviour
{
private InputHandler _input;
[SerializeField] private float moveSpeed;
[SerializeField] private float rotateSpeed;
private void Awake()
{
_input = GetComponent<InputHandler>();
}
private void Update()
{
Vector3 targetVector = new Vector3(_input.InputVector.x, 0 , _input.InputVector.y);
Vector3 movementVector = MoveTowardTarget(targetVector);
RotateTowardMovementVector(movementVector);
}
private void RotateTowardMovementVector(Vector3 movementVector)
{
if (Math.Abs(movementVector.magnitude) < 0.01f) return;
Quaternion rotation = Quaternion.LookRotation(movementVector);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotateSpeed);
}
private Vector3 MoveTowardTarget(Vector3 targetVector)
{
float speed = moveSpeed * Time.deltaTime;
Vector3 targetPosition = transform.position + targetVector * speed;
transform.position = targetPosition;
return targetVector;
}
}
Do you have any suggestion on how to avoid this strange transform behavior after collision?
Thanks!
screenshot-2.png
(204.8 kB)
screenshot-1.png
(215.5 kB)
Comment