I'm creating a project in which I have a sphere GameObject which has empty game object as a child. A line renderer component is attached to the this empty game object.
I have made the sphere to look at the touch direction so that the line renderer of the child object also faces towards the touch position. It works fine when the sphere is rotating in one axis.
But the problem occurs when I apply a force to the sphere and it starts rotating in all axis just like a normal ball. But the line renderer attached to it is stuck to its face and when the sphere faces downwards, the line renderer goes into the ground.
Code for Line Renderer.
using UnityEngine;
using System.Collections;
public class LineRenderer : MonoBehaviour {
private LineRenderer lineRenderer;
private Vector3 finalTouchPosition;
// Use this for initialization
void Start () {
lineRenderer = gameObject.GetComponent<LineRenderer> ();
}
// Update is called once per frame
void Update () {
Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hit;
lineRenderer.SetPosition (0, ray.origin);
if (Physics.Raycast (ray, out hit)) {
lineRenderer.SetPosition (1, hit.point);
}
}
}
Code for rotating the object with touch.
if(theTouch.phase == TouchPhase.Moved)
{
Vector3 tempTouch = new Vector3(theTouch.position.x ,theTouch.position.y, myCamera.position.y - targetObject.transform.position.y);
fingerPosition = Camera.main.ScreenToWorldPoint(tempTouch);
targetObject.transform.LookAt(fingerPosition);
isRotating = true;
}
I want the line renderer to always be parallel to the ground but originate from the sphere or face of the sphere. I've tried many things. But still haven't found the solution.
Your question seems a little confusing, but it seems like you want a ball to rotate around a line. The ball to rotate at its own will and the line to just stay relative to the ball and no rotation.
If this is correct. What I suggest is having two objects. the ball and then an empty/invis object. The ball rotates and moves and just takes the empty object with it by movement, no rotation. Put the line renderer on the empty object and in the hierarchy have invis object be the parent of the ball. Move the empty object with the ball physics and bamn rolling ball, that responds to touch.
Sorry, if Im bad at explaining. And if you dont know when you parent something in the hierarchy they move together.
Related
Summary:
I have a gameobject that have a rock mesh. However, the bottom of the mesh is hallow and ugly. I want to place it on a mesh that looks like a hill, so that the player cannot see the gameobject's ugly and hallow bottom.
I have a script that uses raycast to place the rock. The raycast is above the mesh. When I raycast downwards, I get a Vector3 on the hill looking mesh. I place that rock on that point, and I can see its bottom! How to avoid that using C# code?
Here is my full question:
How To:
Rotate and move a GameObject, which have a "mesh" as its component, so that it sits on another mesh "perfectly" without seeing the GameObject's bottom through c# script in Unity.
How it looks like now
What I want to achieve
Any kinds of help is appreciated!!
Here's a snippet of code which uses the raycast hit's normal value to rotate the rock mesh.
The normal is a vector heading outwards (perpendicular) of the mesh geometry between vertices:
https://en.wikipedia.org/wiki/Vertex_normal#/media/File:Vertex_normals.png
If you place this script on the rock mesh, it will tell the rock mesh that its upward vector is the same as the normal where the raycast point is.
using UnityEngine;
public class StickToTerrain : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit terrainHit))
{
transform.up = terrainHit.normal;
}
}
}
}
I could really need some help with my GameObjects.
I am working on a game in which I want a pick-up Item to create a Physics Force explosion to blow away the enemies. I made a simple Bomb-Object to test this idea. I added a straightforward code, using a loop to collect all the colliders within its radius, to then addForce to these colliders. Now the code is working properly, but not all my GameObjects are reacting properly.
I looked into why this is, and I noticed that my Collider keeps falling away from the GameObject as soon as I add a RigidBody component to the object. The RigidBody is needed for the AddForce impact. When I remove the rb, the collider stays in place, but the object does not react to the Physics Force.
I added some images to illustrate what I mean:
Image of the Collider of the leaf sinking away..
Example image of objects which DO react to the AddForce.
I already tried to:
Copy/Paste all component settings from the reacting Cube and stone
Gameobjects to the Leaf Gameobject while disabling all other code
such as the c# scripts. The Collider & RB do not fall through the
floor but when Physics Force hits the Collider is blown away while
the GameObject keeps its position.
Try different GameObjects/Collider types.
Removed the water.
Play with amount of force/radius of the bomb.
Edited 'Tag' and 'Layerstyle' of GameObject.
The 'Explosion Code' is added below, however, I don't think the problem is in the code. I added the code to the Main Camera of my scene, and added a simple sphere as the 'bomb' GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public GameObject bomb; //set the position of the explosion
public float power = 10.0f;
public float radius = 10.0f;
public float upForce = 0.0f;
private void FixedUpdate()
{
if (Input.GetKeyDown("space"))
{
print("space key was pressed");
Invoke("Detonate", 1);
}
}
void Detonate()
{
Vector3 explosionPosition = bomb.transform.position; //set the position of our explosion to the position of the bomb.
Collider[] colliders = Physics.OverlapSphere(explosionPosition, radius); //collects all colliders within the radius.
foreach (Collider hit in colliders) { //for each individual collider the following code is ran.
Rigidbody rb = hit.GetComponent<Rigidbody>(); //declare'rb' rigidbody. Get rb component from each collider
if (rb != null)
{
print("BOOM!");
rb.AddExplosionForce(power, explosionPosition, radius, upForce, ForceMode.Impulse); //add force to each collider
}
}
}
}
How do I make the Rigidbody, Collider and GameObject of the leaf hold onto each other like the standard 3D object 'cube', so that I can make these blow away with the Physics Force just like the other models?
Thank you for your time, I have been trying things and looking around on the Internet for hours now but can't seem to find any solution.
What happens if you add the rigidbody in stop mode and press play? Does it move away in a similar manner? This may, and is expected to happen, if your colliders intersect with each other. As soon as you add a rigidbody, they find themselves trapped in a serious collision.
If you don't want to modify the scene, you can fiddle with the collision matrix in project settings / physics
I am working on a game which has strong base on spherical gravity. But somehow my code is not working as expected. So please have a look at my code and tell me how can I make my spherical gravity work.
public class CircularGravity : MonoBehaviour {
private Rigidbody2D rigid;
[SerializeField]
Transform planet;
[SerializeField]
float acceleration = 0.81f;
// Use this for initialization
void Start () {
rigid = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
rigid.AddForce((planet.position - transform.position).normalized * acceleration);
transform.rotation = Quaternion.LookRotation(planet.position - transform.position, transform.up);
}
}
Problem elaboration. Project is 2d. it contains a circle sprite as a planet with a collider and hexagon has a player(just a prototype) with collider and rigidbody. This script is attached to the player(hexagon). According to my logic rigidbody should apply a force to the player and push it towards the planet and it should face the planet. So even if the player is on the downward side of circle it shouldnot fall instead it shall be pushed toward the planet. But all the colliders are being neglected and player is just going to strange position
First things I would check...
Make sure the origin of your sprite is actually in the center of the image. If it's in the corner the player will be pulled toward the corner.
Make sure both the planet and player have rigid bodies and colliders. Click on the collider and make sure the edge lines up with you shapes.
Make sure both the planet and the player have their z set to zero. Lock z in both rigidbodies.
I am trying to make a game where the camera follows the user, as they move around. I made the camera a child of the player and in the editor, the camera rotates around the player fine. When I play the game (in Unity) and rotate the player, the camera literally rotates instead of rotating around the player to keep the same regular following distance.
I use transform.Rotate() to rotate the player by the way.
In Summary:
Looking for camera that follows player in 3D game, that does not look different when the player turns.
issue is that the camera appears in the editor to rotate around the player perfectly, but not when transform.Rotate() is called on it during runtime in Unity.
All help is appreciated, tyvm for help.
I made the camera a child of the player and in the editor
Everything went down by doing this. You don't make the camera a child if you want it to follow the player.
What you do is to get the distance between the camera and the player in the Start() function. This is also called offset. In the LateUpdate() function, continuously move the camera to the Player's position, then add that offset to the camera's position. It is as simple as that.
public class CameraMover: MonoBehaviour
{
public Transform playerTransform;
public Transform mainCameraTransform = null;
private Vector3 cameraOffset = Vector3.zero;
void Start()
{
mainCameraTransform = Camera.main.transform;
//Get camera-player Transform Offset that will be used to move the camera
cameraOffset = mainCameraTransform.position - playerTransform.position;
}
void LateUpdate()
{
//Move the camera to the position of the playerTransform with the offset that was saved in the begining
mainCameraTransform.position = playerTransform.position + cameraOffset;
}
}
I'm using my camera as a child gameobject of my ball, so when I move my ball camera comes with him. But the problem is I'm using rigidbody.addForce(), so when ball rotates the camera rotates with it, too.
So what should I do not to rotate my camera but only move it with my ball?
void FixedUpdate()
{
rigidbody.addForce(Input.getAxis("Horizontal"), 0, Input.getAxis("vertical"));
}
There are several ways to solve this, I'll list a few.
The first, if you don't care if your ball rotates or not, you can just disable the rotation on the ball. If you open the Constraints section in the rigidbody component, you can freeze the rotation so that the ball won't rotate.
Alternatively, you can write a script that keeps the camera always oriented a certain way. Depending on if you want the camera to rotate around the ball on any plane depends on the way you would implement this.
The third option, which is cleanest, is to not have the camera be a child of the ball. A minimal component to do this would look like this:
public class TargetFollow : MonoBehaviour
{
public Transform Target;
public float DistanceFromTarget;
void Update()
{
transform.position = Target.position + new Vector3(0, 0, DistanceFromTarget);
transform.LookAt(Target);
}
}
Just drag your ball into the 'Target' slot in your component. Keep in mind, this is super bare bones. You may want to add more variables to better control the direction the camera should be from the ball, or perhaps something that grabs a snapshot of the direction and distance the camera is from the ball in the Start method.