- Home /
Moving a player smoothly without breaking collisions?
I'm working on a 2D platformer and currently to move the player I'm simply editing its transform. This is smooth way of moving my character, but unfortunately it doesn't work for my collisions as my player is teleported into blocks and forced back out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour {
static float speed = 0.07f;
public Transform player;
public PolygonCollider2D playerCollider;
public Rigidbody2D playerRigid;
public Transform sightStart;
public Transform sightEndRight, sightEndLeft;
Vector3 goRight = new Vector2(speed, 0);
Vector3 goLeft = new Vector2(-speed, 0);
Vector3 goHome = new Vector3(-18.275f, 8.028f, 0f);
void Update ()
{
if (((Input.GetKey ("a") || Input.GetKey ("left")) && player.position.x > -28.65f)) {
player.position += goLeft;
}
if (((Input.GetKey ("d") || Input.GetKey ("right")) && player.position.x < 20.22f)) {
player.position += goRight;
}
if ((Input.GetKeyDown ("w") || Input.GetKeyDown ("up")) && onGround()) {
playerRigid.AddForce (new Vector2 (0, 4), ForceMode2D.Impulse);
}
if (player.position.y < -12) {
player.position = goHome;
}
}
bool onGround () {
GameObject[] solidObjects = GameObject.FindGameObjectsWithTag ("solidObject");
foreach (GameObject solidObject in solidObjects) {
if (playerCollider.IsTouching (solidObject.GetComponent<BoxCollider2D> ())) {
return true;
}
}
return false;
}
}
Is there a way to move my player so that it retains the smooth movement but collides with object correctly? I'd prefer not to use AddForce() unless it keeps my smooth movement.
Including code would be very helpful as I'm new to Unity.
alter the velocity on FixedUpdate and use interpolation mode on the rigidbody
It would be great if you could include some code :-)
Answer by hectorux · Jun 28, 2018 at 11:03 PM
You could use a character controller component, works similar of the transform, instead you have to reference it and use the method Move(). Also detect collision, but if you want to detect triggers it wont work, althoug you can just put a collider too and will work
It would be great if you could include some code :-) thanks
CharacterControler cc;
void Start(){
cc=getComponent<CharacterController>();
}
void Update(){
cc.$$anonymous$$ove(Vector3 direction* speed* Time.detlaTime)
//It work like a translate but it will collide
}
Your answer
Follow this Question
Related Questions
Make characters go through each other 1 Answer
Smooth Collisions 2D 0 Answers
Rigid Body Movement (Mobile Issue) 3 Answers
Projectile Ricochet Issue. Travels along the surface rather than reflecting off of it 2 Answers
Rolling Barrels through Platforms 0 Answers