I have a 'player' 3D Object and a 'circle' 3D Object. The player can move towards the circles one by one already.
I need the circles to generate randomly in front of the player when spacebar is pressed, e.g spacebar pressed then one circle generated, spacebar pressed again then another circle generated and so on.
As in randomly generated, it needs to spawn on the radius of the existing circle, e.g 2 units away from the circle anywhere in front that is not behind (180 degree)
All this text may make the question seem complicated but all I really need is another circle created in front of the existing one.
It would also be helpful if you could use some sort of random rotation of the player in order to generate in front of the player.
This is my code so far, feel free to completely wipe my original code in the answer:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateObject : MonoBehaviour
{
public Vector3 playerPos;
public GameObject yourObject;
// Use this for initialization
void Start()
{
playerPos = playerPos.transform.position;
Instantiate(yourObject, new Vector3(playerPos.transform.position.x + 5, playerPos.transform.position.y, playerPos.transform.position.z), Quaternion.identity);
}
// Update is called once per frame
void Update()
{
}
}
Thanks in advance!
you can rotate your player around your Up Vector between your max and min angle then use your distance and direction to find the new position
for the random angle part you can generate a random number with
RandomAngle=Random.Range(MinAngle,MaxAngle);
then use it with
Quaternion.AngleAxis(RandomAngle, playerUpVector)
to rotate it around your players Upvector, I dont know what you used for your Up vector but normally it is Vector3.up
then multiply it by your players direction(playerLocalDirection) that which normally is Vector3.forward
Vector3 newPos= myPos + Quaternion.AngleAxis(RandomAngle, playerUpVector) * playerLocalDirection * DistanceFromPlayer;
Related
I made a 2D Grappling Game in which the player is supposed to travel through the map by grappling from object to object. Right now I just dragged some of those prefabs into my scene in order to try out the gameplay. I also have some power-ups and obstacles. However, I want the map to be infinite on the x-axis. To achieve that I want to randomly instantiate my map prefabs when the player or better the cameras bounds move. Also I want the script to work with different probabilities and random spawn positions for the map prefabs.
I am not really sure how to approach this as I don't know whether it would make sense to use some sort of randomly generated chunks that get instantiated or something else.
The only scripting I have done for now is this:
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class MapBuilder : MonoBehaviour
{
private Vector2 screenBounds;
[Header("Map Prefabs:")]
public GameObject Rec;
public GameObject Circle;
public GameObject Coin;
public GameObject Thorn;
public GameObject Time;
public GameObject Boost;
public GameObject Multi;
public GameObject Disabler;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
}
SceneView
Game Screenshot
Best approach depends a lot on what exactly you want. Here's the first option that came to my mind.
Start by generating the middle rectangle and all rectangles around it
When the camera center goes beyond one of the edges, generate new rectangles so that the map around your camera is always generated. For instance, if your camera goes to rectangle (1,0), generate (2, -1), (2, 0) and (2, 1)
Generating a rectangle:
Generate as many map elements as you want to have on that rectangle.
Randomize their positions within that rectangle.
I am looking at developing a game within Unity by using C#
The game will take the gyroscope orientation and rotate accordingly to the direction of which the phone is rotated.
I am curious of how this would work, I understand how I would be able to read and update the gyroscope orientation however I am unsure on how to assign this to a world to rotate. There will be a player on world which will be the next challenge to prevent the player clipping through the world when it is rotated.
Hence the world should rotate around the players current location.
I currently have no code as I am in the process of designing this, however i am unable to get the logic of how to make this work within my head
Thankyou
If I get your objective right, I guess rotating the camera like in a Fist-Person game should be enough, and would be way simpler than rotating the whole world while keeping the player static.
This is how I would go about it, first I wouldn't rotate the world, as that is alot of objects to rotate, but if you really wanted to you could parent all of the world to a single game object, then rotate that object about an axis based off of the players position(See this: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html).
The simplest way is to attach your main camera to your player(Drag and drop it on your Player Object in your hierchy), then rotate your player.
for an example you can test on your machine without the gyroscrope:
using UnityEngine;
public class rotatorScript: MonoBehaviour {
void Update() {
// Will Rotate based off of left/right arrows
float rotator = -Input.GetAxisRaw("Horizontal");
// Move up or down based off of up/down Arrows
float verticalDirection = Input.GetAxisRaw("Vertical");
// Do the actual movement... using space.self so it is based on the player not the world.
transform.Translate(Vector3.up * verticalDirection * Time.deltaTime * 5f, Space.self);
transform.Rotate(0f,0f,90f * Time.deltaTime * rotator);
}
}
This script would be attached to the player.
The code that rotate the turret is kind simple:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotateturret : MonoBehaviour
{
public Transform target;
public Transform partToRotate;
public float turnSpeed = 10f;
private void Update()
{
transform.LookAt(target);
}
}
The target in this case is rotatingaround the turret in fixed speed but changing the height randomly.
If this script RotateTurret if I attach it to the Turret child part it will rotate and will look at the target. Like doing LookAt.
This is a screenshot of the Turret part:
And if I attach the script to the Pylon part it will rotate slowly and will always stay behind the target it will not rotate fast enough.
Screenshot of the Pylon part:
My problems are: What part of the turret should I rotate ? The logic say the Pylon I think.
Second is how should I calculate the speed the turret should rotate ? Does it always should facing perfect to the target ? Or sometimes if the target is moving in random speeds the turret will not facing it all the time 100% ? What is the logic in this case ? Just using LookAt is not enough. And I'm not using physics yet that's another problem I guess. If both turret and target will use physics but for now not sure how to do the turret logic (Or should I call it AI).
For testing I tried this script too:
public class Rotateturret : MonoBehaviour
{
public Transform target;
public Transform partToRotate;
public float turnSpeed = 10f;
private void Update()
{
Debug.DrawRay(transform.position, transform.forward, Color.green, 1000);
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
}
And again if I will rotate the Turret it will be more accurate but if the pylon it will be behind the target. And who said the speed of the rotating of the turret should be 10 and 20 or 50 or 1 ? There is no much logic in this script either I guess.
Another thing is that in the future I will want also to rotate the Gun to shoot bullets. So the rate fire and when to start firing that's another problem maybe that will be another question, But I guess the firing shooting bullets is also relevant to the turret rotating logic.
Firstly, note that from your screenshot, the Pylon gameobject's forward direction (blue arrow) is perpendicular to the turret barrel's direction. Thus, attaching your script on that gameobject will not produce your desired behaviour.
When it comes to the implementation of a turret's movement, it depends greatly on the context of your game.
For example, if the turret is to be used in a Tower Defence game where it should never miss, then typically the turret's rotation and shooting animation should just be an effect. Your actual damage dealing to the target will be done via script directly (e.g searching for viable target in range and sending an onShoot event). In this case, a transform.lookAt() is good enough, as it produces a reasonable visual effect.
However, if your turret is to be used in a First Player Shooter game, expect then that it's rotation will be controlled by the player (either via transform or rigidbody physics). Whether or not the turret should deal damage to the enemy depends on whether the projectile (simulated via physics with rigidbody and collider) hits the enemy or not. In this case, you have to limit your turret's maximum rotation speed. How much the threshold is depends on how realistic you want it to be.
Firstly, there is a LookRotation overload that takes the axis as a second parameter, so if you try
Quaternion lookRotation = Quaternion.LookRotation(dir,Vector3.up);
the rotation will always be around a vertical axis. This way you can split up motion into seperate axis as you would with a mechanical device (i.e. the pylon only rotates around a vertical axis)
As for the second part, i.e. how to make the turret hit the target, there's several approaches you can take:
You could, for example take the distance between the turret and the target, divide bullet velocity by target velocity, and take target.transform.forward multiplied by that ratio and the distance (this is from head, but you get the idea).
A bit more interesting alternative is to take the opportunity to learn about PID controllers, turrets are a fantastic example of how much can you do with a very simple controller.
PID stands for Proportional, Integral and Deriviative, and you compute your actuator output (i.e. force that drives your rotation) based on those three ways of looking at values.
In the most simplitied form it works like that: Proportional is your direct delta - how much of an angle away from your target angle you are (or from the target forward point). Than you average out that parameter (i.e. lerp the current value towards the target or using moving average) by a signifficant amount, this is your integral part - it will follow the target in a much slower way. Now if you subtract your averaged (integrated) value from your current (propoprtional) value, you get something that represents your change, this can be used as a deiviative component. Now this last part is what makes the turrent react to when the target is changing trajectory, you can make the output overshoot the change, or tune it in multiple other ways
How to Roll/rotate the cube on it's edge?(Like this)
I read a couple of articles and answers to the questions but still not what I need.All I learned ,is that I need to create a gameobject in the center of the Cube and 4 others on the pivots.Something like that
And what's next, should I use Quaternions or transform.Rotate?Is the hierarchy correct?
I was about to tell you to use an external 3D software to set the pivot point to the location in your screenshot but it looks like you want to do this with multiple pivot points so you will to use empty GameObjects to accomplish this.
From your screenshot, you seem to be on the right track.
1.Create empty GameObjects and position them in the edges you want to rotate the cube around then place them under the cube.
2.Use transform.RotateAround not transform.Rotate to rotate the cube. The first parameter should be the edge pivot point. The second parameter is the axis you want to rotate the cube against. The third one is the angle.
//cube to rotate
public GameObject cube;
//Assign dge pos from the editor
public Transform edgePivotPoint;
public float rotSpeed = 60f;
void Update()
{
cube.transform.RotateAround(edgePivotPoint.position, Vector3.back, rotSpeed * Time.deltaTime);
}
Note, if rotating the wrong way, try replacing Vector3.up with Vector3.down, Vector3.left, Vector3.right, Vector3.forward and Vector3.back. The one to use depends on your scene setup but trying them will get you to the one
I need to find a way to make a 3D boat, appear to be buoyant in the water. Currently I am using a boat with a flat bottom and making it slide along the terrain, which is just below the water. This is giving the illusion of buoyancy, but not really what I'm looking for.
The boat moves using
this.transform.Translate(Vector3.left * Time.smoothDeltaTime * ((speed) + 1));
The boat turns using
this.transform.Rotate(Vector3.forward*Time.smoothDeltaTime*(int)(30*horizontal));
The boat has a RigidBody that uses gravity, does not interpolate, and has a Continuous Dynamic collision Detection. It also uses a convex Mesh Collider, with Smooth Sphere Collisions.
The Water has a Box Collider that is used as a trigger.
Now I need a way to make the boat seem to float in the water programmatically.
That means it
Wobbles when it hits something
Doesn't touch the bottom of the "river"
Corrects its rotation to stay flat on the river (doesn't stay crooked after hitting an island or other obstacle)
I would like to do this so that I can give the base of my boat the correct shape so that it can have more realistic collisions with underwater obstacles.
Additional to my comment, if really you want it to be buoyant, you have to make it non-kinematic and react to gravity and the water has to bee a volumetric mesh (or a box as you use, but that's less accurate, do not work with waves if you use water with wave effect).
Basically you'd want to add (at least) 4 objects to your boat and place rigidbody inside it and a script which will apply an upward force which is greater than your gravity.
Then in your OnCollisionStay method set a bool. Maybe something like this (on top of my head)
using UnityEngine;
using System.Collections;
public class Buoyancy : MonoBehaviour {
public float UpwardForce = 12.72f; // 9.81 is the opposite of the default gravity, which is 9.81. If we want the boat not to behave like a submarine the upward force has to be higher than the gravity in order to push the boat to the surface
private bool isInWater = false;
void OnTriggerEnter(Collider collidier) {
isInWater = true;
rigidbody.drag = 5f;
}
void OnTriggerExit(Collider collidier) {
isInWater = false;
rigidbody.drag = 0.05f;
}
void FixedUpdate() {
if(isInWater) {
// apply upward force
Vector3 force = transform.up * UpwardForce;
this.rigidbody.AddRelativeForce(force, ForceMode.Acceleration);
Debug.Log("Upward force: " + force+" #"+Time.time);
}
}
}
And place this on all 4 buoyancy objects (together with a collider or trigger of course). When the object is in water, it will push the boat upwards, if it's over the water, it will be pulled down by the gravity until it reaches water again where it will be pulled up again until it finds a balance.
P.S. If you want to move the boat, you will use the this.rigidbody.AddForce(Vector.forward * 5, ForceMode.Force) (or ForceMode.Accelerate) to move the boat
Use the Buoyancy script. Just add this to the boat, and add the water level (its y value) in the code. Also it is best to use addForce instead of translate to move the boat.
If you want to make the boat react more realistically, you should also put its center of gravity lower, this way it will "wobble" and it stays right side up.