Search Unity

My Movement script blew up, please help

Discussion in 'Scripting' started by Volt777, Sep 2, 2018.

  1. Volt777

    Volt777

    Joined:
    Aug 6, 2018
    Posts:
    16
    this is the scripts

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class RBMoveCamAndPlayer : MonoBehaviour {

    Rigidbody RB;
    public Transform Moaincam;
    public Transform PlayerBody;
    public float speed;
    public float Sensitivity;

    void Start () {
    RB = GetComponent<Rigidbody>();
    }


    void Update () {
    float Hori = Input.GetAxis("Horizontal");
    float Verti = Input.GetAxis("Vertical");
    float MouseX = Input.GetAxis("Mouse X");
    float MouseY = Input.GetAxis("Mouse Y");

    MouseX *= Sensitivity;
    MouseY *= Sensitivity;
    Verti *= speed;
    Hori *= speed;

    Vector3 Movement = new Vector3(Verti, 0, Hori);
    Vector3 jump = new Vector3(0, 6, 0);
    Vector3 camturn = new Vector3(0, MouseX, 0);
    Vector3 camup = new Vector3(-MouseY, 0, 0);

    PlayerBody.transform.Rotate(camturn * Time.deltaTime);
    Moaincam.transform.Rotate(camup * Time.deltaTime);
    RB.MovePosition(this.transform.forward + Movement * Time.deltaTime);
    }
    }

    and the character goes to 0, 0, 0 in location and Spaatzes out with the terrain.
     
  2. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
  3. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    387
    I think it would also be better to store the Vector3 variables, that you declare I'm Update, as class variables rather than setting them every frame.
     
  4. samizzo

    samizzo

    Joined:
    Sep 7, 2011
    Posts:
    487
    Rigidbody.MovePosition moves the rigid body to the specific position. You're passing a relative movement into it though. You should do something like:

    Code (csharp):
    1.  
    2. RB.MovePosition(transform.position + transform.forward * Movement * Time.deltaTime);
    3.  
    I.e. move the rigidbody from its current position in the forward direction by the amount defined by the input.

    Also you probably want to do that in FixedUpdate instead of Update.

    Sam