Unity Android:Rigidbody - unity3d

I'm working with an android project in Unity 3d.
I would to roll the sphere at the surface of a cube.
However, when I clicked the play button it returns error message:
Assets/Scripts/Player.js(4,1): BCE0005: Unknown identifier: 'rigidBody'.
My code:
function Start () {
rigidBody.velocity.x=15;
}
Rigidbody components has been already added to the sphere.
I would like to seek solution to the error generated.

I don't know if you've set a GetComponent variable on the rigidbody, but you may have to strip the case out of that.
For example:
rigidBody.velocity.x=15;
would be:
rigidbody.velocity.x=15;
Hope that helps.

First, it's "rigidbody" not "rigidBody"
Second, starting with Unity 5 + something you cannot use "rigidbody"
anymore, so you have to use GetComponent
Resuming, to use "rigidBody" as it is, you have to initialize it first like others answered you already:
//link you rigidbody here:
public Rigidbody rigidBody;
function Start() {
//Or if the script is on the GameObject that has the rigidbody component:
//rigidBody = GetComponent<Rigidbody>();
rigidBody.velocity=new Vector2(15,0);
}

I think you forgot to initialize a Rigidbody. Also you cannot assign a velocity like this because rigidBody.velocity.x is a read-only value.This code might help you:
public Rigidbody rigidBody;
function Start(){
rigidBody.velocity=new Vector2(15,0);
}

You haven't initialized the variable "rigidBody".
I don't think that's your objective though.
If you have the script added to the sphere as a component, you don't have to use getComponent. Instead it's going to be just:
"Rigidbody.velocity.x=15;"
You might have to use a "new Vector3(x,y,z);" to pass the new velocity on. In that case the code would look like this:
Rigidbody.velocity = new Vector3(15,Rigidbody.velocity.y, Rigidbody.velocity.z)*
I'm working in 2D right now, so my parameters of Vector3 might be off.
I thought Rigedbody was correct, but it might be rigidbody - see above.
In any case, don't forget your colliders. Ridged bodies don't automatically collide with other objects, but they are subject to gravity. Once I finally figured that out, I just dropped my character 20 feet onto pavement out of joy. Rendering blood is surprisingly easy if you're not that picky.

you need add rigidbody components in inspectors first then :
Rigidbody sphereRigidbody;
function Awake(){
sphereRigidbody = GetComponent<Rigidbody>();
sphereRigidbody.velocity = new Vector3(15,0,0);
}

for c#
You might want to cache it first.
private Rigidbody rigidbodyCached;
//cache
void Start(){
rigidbodyCached = this.GetComponent<Rigidbody>();
}
//for velocity movements use FixedUpdate instead of Update
void FixedUpdate(){
rigidbodyCached.velocity = new Vector3(15,0,0);
}

if you working with unity less than 5 (I guess) you have access to use components of game objects like rigidbody or audiosource but in unity 5 and later you need to add a reference to that in neither in awake or start function like this code
private Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
// AND AFTER YOU ADDED THE REFERENCE FOR RIGIDBODY
// THEN CHANGE THE VELOCITY LIKE THIS
rb.velocity.x = 20;
}

Related

Rotate a Rigidbody to align with an orientation

I'm currently setting the rotation of a player object so that it "stands up" relative to the spheroid the user stands on.
However, that will break Rigidbody physics.
I already have the direction of gravity as a Quaternion, how can add torque to the Rigidbody so that it aligns with that direction?
Here's my code on Github, which does allow the player to move around the surface of the planet.
I have tried various approaches using AddTorque and Vector3.Cross, but they have all only ended in the Rigidbody spinning wildly.
Instead of using transform whenever a Rigidbody is involved rather first calculate the needed final Quaternion ad then apply it using theRigidbody.MoveRotation which does not break the physics.
The same also accounts to the position where you should rather use theRigidbody.MovePosition.
Both should be used in FixedUpdate so
either move the entire code from Update to FixedUpdate
or split the input and the physics and do your API stuff in Update, store the relevant values into fields but apply anything related to the Rigidbod transformations reactive in FixedUpdate.
Your code is quite complex so I will only give an example as a pseudo code and hope you can take it from there
So instead of doing e.g.
private void Update ()
{
player.transform.position = XYZ;
// Applies a world space rotation
player.transform.rotation = XYZW;
// Adds a relative rotation in local space
player.transform.Rotate(x,y,z);
}
You would rather do something like
[SerializeField] Rigidbody playerRb;
private Vector3 targetPosition;
private Quaternion targetRotation;
private void Awake ()
{
if(!playerRb) playerRb = player.GetComponent<Rigidbody>();
}
private void Update ()
{
targetPosition = XYZ;
targetRotation = XYZW * Quaternion.Euler(x,y,z);
}
private void FixedUpdate ()
{
playerRb.MovePosition(targetPosition);
playerRb.MoveRotation(targetRotation);
}

How to create a projectile Script in Unity

so recently my friends and I are trying to make a game for fun. Currently, I hit a wall and not sure how to do this. I am trying to create a simple base script where I have the character move and attack with right click. If it hits the ground, it will move there and and if in range of a target, it will send a projectile. So the game is creating the projectile but its not actually moving. Can anyone tell me what I should probably do. At first, I thought to just make it all one script but now I am thinking it be best to make another script for the projectile.
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
if(Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out hit) && hit.transform.tag == "Minion")
{
if(Vector3.Distance(this.transform.position, hit.point) <= atkRange)
{
GameObject proj = Instantiate(bullet) as GameObject;
proj.transform.position = Vector3.MoveTowards(this.transform.position, target, atkSpd);
}
}
else if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, speed))
{
agent.destination = hit.point;
}
}
}
So this is what I originally had. I am pretty sure I did something wrong here. Also I am not sure if I should have another script for the projectile itself or if it is not necessary. Thank you for any help or tips on what to do.
For starters, I'd advize using a Rigidbody component and letting physics handle movement but if you'd like to use Vector3.MoveTowards, it'll be a bit of work:
Vector3.MoveTowards is something that needs to be called every frame. I'm guessing bullet is your prefab so you'll want to make a new script for the movement and place it on that prefab:
public class MoveToTarget : MonoBehaviour
{
private float _speed;
private Vector3 _target;
public void StartMovingTowards(Vector3 target, float speed)
{
_target = target;
_speed = speed;
}
public void FixedUpdate()
{
// Speed will be 0 before StartMovingTowards is called so this will do nothing
transform.position = Vector3.MoveTowards(transform.postion, _target, _speed);
}
}
After you've attached this to your prefab, make sure you grab a reference and get it started when you instantiate a copy of your prefab:
GameObject proj = Instantiate(bullet) as GameObject;
var movement = proj.GetComponent<MoveToTarget>();
movement.StartMovingTowards(target, atkSpd);
If you instead go the physics route, add a Rigidbody component to your bullet prefab, and get a reference to that instead of making the MoveToTarget script:
GameObject proj = Instantiate(bullet) as GameObject;
var body = proj.GetComponent<Rigidbody>();
Then you can just apply a force and let physics take over:
body.AddForce(target - transform.position, ForceMode.Impulse);
Don't set the position like you currently are
proj.transform.position = Vector3.MoveTowards(this.transform.position, target, atkSpd);
Instead, add either a characterController or a rigidbody and use rb.addVelocity.

My game object move as soon as it gets some input

I'm trying to learn Unity by myself. I'm recreating pong in 3d with Unity objects. I started a few minutes ago and every time I throw any input into the pad its y coordinate shifts to 2.6, I have no idea why. Can someone help?
public class PadMovement : MonoBehaviour {
private CharacterController pad;
private Vector3 direction;
private Vector3 movement;
[SerializeField] private float speed = 50.0f;
// Use this for initialization
void Start() {
pad = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update() {
direction = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
movement = direction * speed;
pad.Move(movement * Time.deltaTime);
}
}
SOLVED: there was a capsule collider out of place!
Afternoon, I recently copied your code into a 'Unity3d', ".cs", File and actually I created a cube and placed my game into a 2d mode, After this I named my file "PadMovement", after that I dragged it onto my newly created cube, Once I had done that I tried to click play and noticed that my cube didn't have a "CharacterController", attached to my cube, Once I had done that and clicked play I was eligible to have my "paddle", smoothly move around the screen # 50.0f along the X axis.
Knowingly, My Input came from the "Character Controller", My Speed came from the Serial field you had for speed!
Do you by any chance have a CapsuleCollider Component or some other collider on the same GameObject that you have this PadMovement Component on? That sounds like a height where it might just be trying to pop the object out of ground collision.
It should be harmless if that's all it is. If you really want an object to be at y of 0 you can attach it to a parent object and have that parent stay at 0.

Unity Prefab spawn incorrect rotation

I have the following simple prefab:
When I add this to my scene, it looks like this:
Very neat!
Then I have the following script on my Character:
public class MageController : MonoBehaviour {
public GameObject Spell;
public float SpellSpeed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.H)) {
GameObject newSpell = Instantiate(Spell);
newSpell.transform.position = transform.position;
newSpell.transform.rotation = Quaternion.LookRotation(transform.forward, transform.up);
Rigidbody rb = newSpell.GetComponent<Rigidbody>();
rb.AddForce(newSpell.transform.forward * SpellSpeed);
}
}
}
The goal is of course to make sure that the fireball is spawned correctly (with the tail behind it)
This works when I stand at 0.0.0; it looks like this:
However, if I turn around it looks like this:
As you can see, the rotation of the fireball is not correct (in the above incorrect image it is flying away from me, however, the tail is in front).
What am I doing wrong? How can I make sure that the tail is always correctly placed?
Update after following the guidance of PlantProgrammer
it still turns incorrectly :(
Look at the image below!
You want to use the forward direction of the player and not it's rotation, when instantiating the fireball. (Remember: transform in your script is the player transform not the fireball transform.) Check https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html. LookRotation will return the rotation based on player's forward and up vectors.
GameObject newSpell = Instantiate(Spell);
newSpell.transform.position = transform.position;
newSpell.transform.rotation = Quaternion.LookRotation(transform.forward, transform.up);
Not part of your question, but I would also suggest letting the fireball fly in the forward direction of itself not the player (as this leaves more room for later modifications)
rb.AddForce(newSpell.transform.forward * SpellSpeed);

Smooth Camera Follow with Voxel Based Sphere

I am very new to Unity and just got done yesterday following the Roller Ball example on the learn page here at Unity3d.
To practice what I have learned I wanted to try and recreate something similar using my own art and making the game different. I have been playing around with Voxel Art and I am using MagicaVoxel to create my assests. I created the walls, the ground etc.. and all is well.
Then came the player object, the sphere. I created one as close to a sphere as possible with magicaVoxel and it rolls fine. However, when using a script to have the camera follow the object it runs into issues.
If I don't constrain the Y axis then I will get bouncing and as far as the x and z axis I get kind of a Flat Tire effect. Basically the camera doesn't follow smoothly it bounces around, stop go etc...
I have tried making the collider larger then the sphere and even using the position of the collider vs the object itself. I have also tried putting the code in Update / FixedUpdate / LateUpdate. What is the proper way to fix or address something like this? Here is my scripts below:
Camera Controller:
public class CamController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
void Start ()
{
// Get the distance between the player ball and camera.
offset = this.transform.position - player.transform.position;
}
void LateUpdate ()
{
this.transform.position = player.transform.position + offset;
}
}
Player Controller:
public class PlayerController : MonoBehaviour {
public float _speed;
void FixedUpdate()
{
// Get input from keyboard.
float _hoz = Input.GetAxis("Horizontal");
float _ver = Input.GetAxis("Vertical");
// Create a vector3 based on input from keyboard.
Vector3 _move = new Vector3(_hoz, 0.0f, _ver);
// Apply force to the voxel ball
this.GetComponent<Rigidbody>().AddForce(_move * _speed);
}
}
Thanks for any help in advance.
You can use the SmoothFollow Script of Unity it self for getting smooth follow of camera.
Here are the steps how you can get the script:
1) Assets->Import Package->Scripts.
2) At the dialog that appears select all the scripts, or just the smooth follow one and hit Import button.
3) Now this script is in your project, and you can attach it to the camera.
Hope this will help you...
Best,
Hardik.