Yo ! I was programming on Unity and I wanted to modify something about the collision detection but when I click on any object but my player 1 on the scene I can’t find that tab. Did I mess up somewhere ? I put a video for more info.
Video : https://www.youtube.com/watch?v=SnmnpgYWKUA&t=1s
// The script that makes the camera follow my player :
using UnityEngine;
public class FollowPerso1 : MonoBehaviour {
public Transform perso1;
public Vector3 offset;
// Use this for initialization
// void Start ()
// Update is called once per frame
void Update () {
transform.position = perso1.position + offset;
}
}
// The script that makes the collision possibles :1
using UnityEngine;
public class Perso1Collision : MonoBehaviour {
public Perso1Movement Movement;
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == “Obstacle”)
{
Movement.enabled = false;
}
}
}
// The script that makes the movements possible :
using UnityEngine;
public class Perso1Movement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 2000f; // <– We declared a variable float to change out forwardForce (REVOIR)… E03
public float sidewaysForce = 500f; // REVOIR
// Use this for initialization
// void Start ()
// voidUpdate : Update is called once per frame (So the force ”speed” will depend on how many FPS your PC has)
void FixedUpdate () // FixedUpdate is better to calculate Physics in Unity (”makes stuff looks smoother when you collide with stuff”. Ref. Brackeys EP.2 HTMVGIU)
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime); // <– NOTE : Gotta understand Time.deltaTime better
if (Input.GetKey(“d”)) // <– QUESTION : Why not ”D” and ”d” instead ? :O
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey(“a”)) // <– QUESTION : Why not ”D” and ”d” instead ? :O
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); // Understand ForceMode.VelocityChange better E06
}
}
}
Thanks!
Just add it? On the bottom of the inspector click on Add Component and either input RigidBody in the textfield on the top or search it under the physics category (should be the 1st entry)
Rigidbody is no default component, you have to intentionally add it to your GameObjects (infact only Transform is default, but the primitives like cubes ofc need a meshfilter and renderer to display, and conveniently also come with boxcollider "out of the box")
I hope it was that and I could help.
Edit:
If you just start out with unity I would suggest to you going over the official tutorials on the unity-website so you get a general idea of how everything works. They are quite well made.
Here is the Rigidbody tutorial for example: https://unity3d.com/de/learn/tutorials/topics/physics/rigidbodies?playlist=17120
Related
I'm a Unity beginner.
I have a problem with my script: in the picture above, Player item does not exist in Move script.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed;
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
transform.Translate(x * speed * Time.deltaTime, y * speed * Time.deltaTime, 0);
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
player.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
}
}
I am not sure if I understand you right, but as this script is the script that belongs to the Player Gameobject, you don't need to specify "public Transform player".
The Gameobject class inherits from the Transform class, so it should work if you try:
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
Maybe to make it more clear:
You don't need to have Player as an "item" that you pull into the according field in the inspector as it was the case if you relate to a gameobject which does not contain the "Move" script.
So, if you attach a script to a gameobject (in this case you attach the script to "Player"), then any methods you script, are directly affecting the gameobject the script belongs to.
E.g. try the following:
void Update() {
if(Input.GetKeyDown("space")) {
Destroy(gameObject);
}
}
You will see that the circle, which forms your player, will destroy itself when you hit the space bar. The parameter "gameObject" refers to the gameobject the script belongs to.
I hope that helps you to understand that you don't need to specify an extra GameObject that needs to be linked to the script, as long as the Gameobject you want to manipulate contains this script.
I'm new to Unity and to C#. I was trying to code a 2D platformer movement script, but for some reasons the code I'm creating doesn't work.
The script is referred to a circle. I've added "Rigidbody2D" and "Circle Collider 2D".
I've tried to use this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
public void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(10, 0, 0);
}
}
}
The code should give an hit to the circle to make it move right, but Visual Studio says that "rb.AddForce" is an error. Can you help me, please?
Are you sure you have actually referenced the rigidbody? Did you drag the rigidbody in the editor? If you have not, you could also say the following (if the script is attached to object that holds the rigidbody you would like to move):
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
1)Make sure your Rigidbody component is NOT set to Kinematic.
2)Depending on the mass and linear drag of the rigidbody, you would need to change the force you apply to it accordingly. The code may be working but you would not see the body moving if you do not apply enough force.
3)Addforce() expects a Vector as an argument. This is your problem.
public float thrust; //set in editor, this is how strong you will be pushing the object
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(transform.right * thrust); //this will move your RB to the right while you hold the right arrow
}
}
4) Set a linear drag of your rigidbody so that it can actually stop after applying the force to it. In order to make it work, set the mass and linear drag both to 1 for example and then just experiment with the thrust variable, it will eventually start moving. After that you can reduce/increase the linear drag and the thrust until you achieve the desired effect.
BONUS
If you wish to use a Vector3D the way you have tried in your code, you could do the following and it will work too:
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(new Vector3(10, 0, 0)); //this will move your RB to the right while you hold the right arrow
}
}
Because of Rigidbody2D implementation it takes Vector2 in constructor as an argument instead of simple Rigidbody which can take Vector3 and Vector2 as Vector3. Consider Vector3 v3 = new Vector2(10, 0); and
Vector2 v2 = new Vector3(10, 0, 0);
Try this
rb.AddForce(new Vector2(10, 0));
or
rb.AddForce(new Vector3(10, 0, 0));
You need to add ForceMode2D.Impulse for it to work:
using UnityEngine;
public class TestControl : MonoBehaviour
{
public Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
rb2d.AddForce(new Vector2(5, 0 ), ForceMode2D.Impulse);
Debug.Log("RightArrow was Pressed");
}
}
}
You can find more info in here: https://www.studytonight.com/game-development-in-2D/right-way-to-move
I have been trying to make a movement script for my player in a 2D game but without success. I do not know why it is not working.
The problem is that the player isn't moving. I have a RigidBody attached and gravity on. (Not sure if gravity makes such a difference but I just thought to mention it.)
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float speed = 10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float mx = Input.GetAxisRaw("Horizontal");
float mz = Input.GetAxisRaw("Vertical");
Vector3 movement = new Vector3(mx, 0.0f, mz);
Debug.Log(movement);
rb.AddForce(movement * speed * Time.deltaTime);
}
}
You may wanna make sure you are adding enough force to actually cause the player to move. Try increasing the force variable incrementally until you see a change. Hope this helps!
I have an animated character , and I need move it forward
I add rigibody to my character , and mover class
when I disable animated controller it moves
my mover class
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().velocity = transform.forward * speed;
}
}
any suggestion how I can approach that
I find out the answer
just uncheck Apply Root Motion
Might want to put it in Update() so its not just called one time.
void Update () {
GetComponent<Rigidbody>().velocity = transform.forward * speed * Time.smoothDeltaTime;
}
When reading this, keep in mind I'm new to both programming and Unity, so I might be missing some terms or tools Unity offer. Please elaborate your answers in an ELI5 manner. Thanks in advance!
I am currently working on some game-physics for a small personal project. Currently I've created a platform, a character and what should be, a following companion.
However, since I'm still not on a level, where I can create perfect code on own hand, I found an "enemy" script and tried to modify it a bit.
It Works to an extend, but it needs some tweaks which I hope I can help aquire with you guys.
This is how it looks now (the orange square is the companion)
It follows the player, and I can tweak the speed to fit as a companion, and not a player. However, as the Picture presents, the companion runs for the center of the player. What I want to create is a companion which follows the player, but still keeps a small gap from the player.
My first thoughts was to create some kind of permanent offset, but I fail to figure out how to do this without messing up the follow function.
I hope you can help me, it will be much appreciated!
Here's the code for reference.
Code attached to Player:
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
//In the editor, add your wayPoint gameobject to the script.
public GameObject wayPoint;
//This is how often your waypoint's position will update to the player's position
private float timer = 0.5f;
void Update ()
{
if (timer > 0) {
timer -= Time.deltaTime;
}
if (timer <= 0) {
//The position of the waypoint will update to the player's position
UpdatePosition ();
timer = 0.5f;
}
}
void UpdatePosition ()
{
//The wayPoint's position will now be the player's current position.
wayPoint.transform.position = transform.position;
}
}
Code attached to companion:
using UnityEngine;
using System.Collections;
public class FollowerOffset : MonoBehaviour {
//You may consider adding a rigid body to the zombie for accurate physics simulation
private GameObject wayPoint;
private Vector3 wayPointPos;
//This will be the zombie's speed. Adjust as necessary.
private float speed = 10.0f;
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
}
void Update ()
{
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y, wayPoint.transform.position.z);
//Here, the zombie's will follow the waypoint.
transform.position = Vector3.MoveTowards(transform.position, wayPointPos, speed * Time.deltaTime);
}
}
bump, I guess ? :)
You can use smooth follow script. I have created a sample class for you. This class has features to follow any given gameobject with some delay and offset. You will have to tweak some values according to your need.
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
[SerializeField]
private GameObject wayPoint;
[SerializeField]
public Vector3 offset;
public Vector3 targetPos;//Edit: I forgot to declare this on firt time
public float interpVelocity;
public float cameraLerpTime = .1f;
public float followStrength = 15f;
// Use this for initialization
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
offset = new Vector3 (5,0,0);//input amount of offset you need
}
void FixedUpdate () {
if (wayPoint) {
Vector3 posNoZ = transform.position;
Vector3 targetDirection = (wayPoint.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * followStrength;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, targetPos + offset, cameraLerpTime);
}
}
}
Attach this class to your player companion, play with different values.
To preserve object orientation your companion schould not be anyways child of your main character.
Your wayPoint doesn't needs to be a GameObject but a Transform instead and your code will looks like better.
If your game is a 2D platform your and your companion needs to be backwards your player it probabli applys to just one axis (X?) so you can decrement your waiPoint in a more directly way by calculating it on your UpdatePosition function like this:
wayPoint.position = transform.position * (Vector3.left * distance);
where your "distance" could be a public float to easily setup.
so on your companion script Update just do:
transform.position = Vector3.MoveTowards(transform.position, wayPoint.position, speed * Time.deltaTime);
I can't test it right now so you could have problems with Vector3 multiply operations, just comment and I'll try to fix as possible ;)