- Home /
Question by
Armadillq · Apr 02, 2018 at 01:53 AM ·
movement scriptplayer movement
Creating a C# script that stops a character when it hits a wall
Im creating a script that has a character move towards a desk and i'd like the force to continue forcing this character towards this desk until he makes contact and then stops completely. This is what i've got. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class deskWalk : MonoBehaviour {
public Transform tr;
public Rigidbody rb;
public float speed = 2f;
// Update is called once per frame
void Start () {
Debug.Log("Moving Now");
}
private void FixedUpdate()
{
rb.AddForce(tr.forward * speed * Time.deltaTime);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject)
{
Debug.Log("Lol im stopped");
rb.velocity = Vector3.zero;
}
}
}
Comment
Answer by toddisarockstar · Apr 02, 2018 at 02:17 AM
using UnityEngine;
using System.Collections;
public class deskWalk : MonoBehaviour {
public Transform tr;
public Rigidbody rb;
public float speed = 2f;
public Vector3 direction;
public bool stopped;
void Start () {
tr = gameObject.transform;
rb = gameObject.rigidbody;
speed = 5;//change this
}
private void FixedUpdate()
{ if (stopped) { direction = Vector3.zero;}
else { direction = tr.forward * speed * Time.deltaTime;}
rb.velocity = direction;
}
void OnCollisionEnter(Collision collision)
{if (collision.gameObject.transform.name == "Name of your desk object") {
stopped = true;}}
}
Thanks a million, edited the code and it worked flawlessly.
no problem, dont foget to mark as correct if its working!
Answer by Armadillq · Apr 02, 2018 at 03:14 AM
Here's the working code...
public class deskWalk : MonoBehaviour {
public Transform tr;
public Rigidbody rb;
public float speed = 2f;
public Vector3 direction;
public bool stopped;
public Transform BankDesk;
// Update is called once per frame
void Start () {
Debug.Log("Moving Now");
}
private void FixedUpdate()
{
if (stopped)
{
direction = Vector3.zero;
}
else
{
rb.AddForce(tr.forward * speed * Time.deltaTime);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.transform.name == "Cube")
{
Debug.Log("Lol im stopped");
stopped = true;
}
}
}