- Home /
Stop player movement if it's Raycast hits an object
I have the debug for my raycasting, and it all seems to work as intended. Now all I need is for the Player to stop moving forward if the Raycast hits another object.
Can I get examples or links to the Script References that can help me do this?
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public PlayerCollision pCollision;
public float speed = 10.0f;
public float jumpSpeed = 10.0f;
public float gravity = 20.0f;
public float JPSpeed = 10.0f;
public Vector3 moveDirection = Vector3.zero;
public Vector3 jumpDirection = Vector3.zero;
// Use this for initialization
void Start ()
{
}
void Jumping()
{
CharacterController playerControl = GetComponent<CharacterController>();
jumpDirection = new Vector3(Input.GetAxis("Horizontal"),0.0f,0.0f);
jumpDirection = transform.TransformDirection(jumpDirection);
jumpDirection *= speed;
playerControl.Move (jumpDirection * Time.deltaTime);
}
// Update is called once per frame
void Update ()
{
//PlayerCollisionCheck Bools
bool canMoveRight = pCollision.pbRight;
bool canMoveLeft = pCollision.pbLeft;
CharacterController playerControl = GetComponent<CharacterController>();
if (playerControl.isGrounded)
{
//Putting this here
if (!canMoveLeft || !canMoveRight)
return;
//Kind of gets what I want. But dissallows left and right movement.
if (Input.GetKeyDown(KeyCode.D) && canMoveRight)
{
moveDirection = new Vector3(1.0f,0.0f,0.0f);
moveDirection *= speed;
}
if (Input.GetKeyUp(KeyCode.D))
{
moveDirection = new Vector3(0.0f,0.0f,0.0f);
}
if (Input.GetKeyDown(KeyCode.A) && canMoveLeft)
{
moveDirection = new Vector3(-1.0f,0.0f,0.0f);
moveDirection *= speed;
}
if (Input.GetKeyUp(KeyCode.A))
{
moveDirection = new Vector3(0.0f,0.0f,0.0f);
}
if(Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
Jumping();
playerControl.Move (moveDirection * Time.deltaTime);
}
}
Okay worse problem: Even though canMoveRight is true, it still doesn't allow me to move right. Probably because of that return;, but if I don't use return, the player is allowed to continue on.
Note: This is a small test for things I want to do that might need something like this later. So I could just use the Unity Collisions but there are things that Raycast can do better.
This depends on your movement script - edit your question and post it.
Currently changing my movement script to contain a bool.
But give me a sec. $$anonymous$$aybe you guys can make it easier on me!
Your answer
Follow this Question
Related Questions
How to make "enemy" have a frustum(cone) view and not a circle radius 2 Answers
I want to click on my screen and make my character move there, having trouble with raycasts. 1 Answer
Raycast Destroys player. 1 Answer
Player takes damage on collision with an enemy 1 Answer
Top Down Shooter Player Controller 1 Answer