New answers tagged

0

I have found another way to do this, void RotatePlayer() { var xDeg = Input.GetAxis("Mouse X") * m_TurnSpeed; transform.Rotate(0f, xDeg, 0.0f); }


0

Add a float rotateSpeed variable from 0.00f to 1.00f and multiple your targetPosition.y by that after Time.deltaTime. I can't test this right this very moment, but I'm fairly certain that should work.


0

For all intents and purposes what you have is essentially the Observer pattern in that you have an input class that maintains a list of callbacks or input handling objects. Other objects can then register with the input system to be notified when certain things happen(in this case when each key has been pressed). I might extend this system to allow users ...


0

The main issue here is that you're trying to call AddComponent with an object rather than a type, which is what's causing your issue. There are 3 possible ways you can fix this: Solution 1 Use AddComponent with a generic function This is very close to what you already have, and only requires you to use GetType rather than the object itself Component[] ...


2

Well, AddComponent's generic parameter expects a type, not a string. AddComponent actually creates an entirely new component of the given type. As far as I know there is no way to get unity to add a new component AND copy the values from another. However, what you seem to be doing is copying ALL the components of one game object to another. If appropriate, ...


1

You actually have two problems here. Problem A: how do I find image pixels to change? Problem B: how do I change specific pixels in Unity with C#? As it happens, problem B is straightforward: you use Texture2D.GetPixels to read an array of pixel colors, change those colors and call Texture2D.SetPixels, followed by Texture2D.Apply. A couple caveats: first, ...


3

Use an override of the SpriteBatch.Draw() function in order to specify what layer you want to draw your sprites on. You are already specifying "FrontToBack" sort mode in your initialization so that is good. Take a look here: https://msdn.microsoft.com/en-us/library/ff433988.aspx More specifically, take a look at the "layerDepth" property. This is what ...


2

Make the gameobject face towards is velocity vector (or its last non-zero velocity vector): float angle = Mathf.Atan2(rigidbody2D.velocity.y, rigidbody2D.velocity.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), rotateSpeed * Time.deltaTime);


3

In your RespawnPlayer() method you are loading a scene at first. Then checking current position, then translating the player to the checkpoint. Upon loading a new scene, everything resets. In RespawnPlayer() after second line execution, the level manager restarts from Start() ignoring the current checkpoint and player translate codes in RespawnPlayer(). In ...


1

Make each of these coloured blobs a seperate gameobject with a spriterenderer. Have the blobs saved as white or grayscale only. Then, just apply the color you want in your SpriteRenderer. It will draw that blob at whatever color you want, and you can easily change the color programatically. entity.GetComponent<SpriteRenderer>().color = new Color(...


6

The best way to do this depends on a few things. I'm going to assume the following - if any of these are incorrect, please let me know and I'll update my answer: You want the closest enemy that is anywhere to the right of the player within a certain range, even if it is at a different height You want true distance, not just the one that is closest in ...


1

Assuming your enemies all have colliders, could you not simply fire a 2D Raycast https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html in a straight line to the right of your player and return the GameObject of the first collider it hits?


0

Made it work by assigning a "Left Side" tag to the enemies on the left and a "Right Side" tag to the enemies on the right. After that I find the closest enemy on a particular side by checking the distance from the enemy to the player and returning the closest one: private GameObject FindClosestEnemy(string side) { GameObject[] enemies = GameObject....


2

All the left enemy are in lower value in x-axis position. Objects on right side are on higher value. Subtract main character's x value from enemy's. Positive results are for enemies at right side.


0

Why just slow down the animation? If you want a slow-mo effect, just slowing the animation means everything else is still going to move at normal speed around you. For that, I would recommend lowering Time.timeScale, which slows down time for everything, including the physics engine. And to answer your question, neither. The best way is to use ...


1

Well your code is very smart but Unity has already done those calculations for you and you can just use void Update () { transform.Translate(0, 0, -Input.acceleration.z); } as it will take the device rotation in the world and translate it into Unity same way it behaves with WASD movement.


0

I did create a few prototypes but nothing too big and the way I used to handle multiple spaces was simply create a game object which contains, world, player etc and than I'd setup some properties that are required by some other spaces for example health, in the game object Whenever called it will get the player's health. that way I could send it to the HUD ...


1

The thing is that with your list you dont know if the element is a weapon or a apple. It's just a GameItem. To be able to use the weapon specific properties you need to retrieve the element and cast it back to a Weapon. For example the update in inventory manager will look like this. void Update() { if (Input.GetKeyDown("a")) { ...


0

you can use Switch statement.in switch statement you can compare experision with your object name then if it was match Do something using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { public GameObject Inventory; // Update is called once per frame void Update () { for(int i =0;i<Inventory....


2

Note that you can supply the SpriteBatch.Begin with a matrix parameter. Use your ingame "virtual screen" dimensions to calculate the scale factor. This way you can draw your game in the native "virtual" resolution and have the matrix do the heavy lifting for you. For example: float xscale = (float)ScreenWidth / VirtualscreenWidth; float yscale = (float)...


1

While I don't know for sure what these two games do, this is how I would do it: Have a Canvas set up with a child GameObject (which can be a prefab) holding all Game Over UI elements. This starts as disabled In the UI GameObject have a script which listens to OnEnable and fills out the relevant info (stats etc) Have a Game Controller that controls the ...


1

If I would implement it in Unity I'd do a dedicated scene with a GUI to show whatever is needed. So in the main scene I would have some script not destroyed on load of a new scene (with DontDestryOnLoad(GameObject go) method) which have all the infos you want to display at the Game Over stage. You could also handle it in a whole scene with variables to ...


2

So long as your 'Text' object contains a Text component, this will work as expected. You may have replaced the Text component with your TextController script, or it was removed some other way. Alternatively, you could change your script as follows: using UnityEngine; using UnityEngine.UI; public class TextController : MonoBehaviour { public ...


2

Graph-based pathfinding calculates an entire path (multiple turns' worth) and you're using only the first step, throwing away the rest, and recalculating every turn. This is wasteful. Keep following the path already computed until you think you need to recalculate it. If you're far away from the target, recalculate infrequently; if you're near it, ...


0

You don't want to check for a path all at the same time for all of your entities. You could try to set a timer on each of your entities, and poll for a new path when the timer expires (instead of waiting for a move). You can further refine this by only reducing the poll timer when the player changes positions (but this is really dependant on your specific ...


0

If you cannot accomplish what you want with Layer Masking, or with the Collision Matrix, then I can suggest an alternative approach to the problem. You can put a tag on the collider objects you want to avoid raycasting, and then doing something like this: void Update(){ if (Input.GetMouseButtonDown (0)) { Vector2 pos = Camera.main....


0

Does Forward-Point shader compiles successfully? Does point light shader program (Program Object) links successfully? Do you call glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) before rendering? Have you enabled depth test (glEnable(GL_DEPTH_TEST))?


0

I'm aware of two ways to do system simulations. One is macro models. You create formulas that takes areas densities in account and evaluate likely traffic at various hours, and that gives you an "extensive variable" (in physics science terms). This technique is the fastest, and most controllable, but potentially less realistic and also boring. The other is ...


2

The simple solution would be to just have each actor calculate the ideal path using A* and then stick to it. Implement each lane of a road as a first-in-first-out queue. The edges in your A* graph should be the lanes, not the tiles. When a car wants to move onto a lane but that lane is already occupied by the maximum number of cars, they simply wait until it ...


1

If I understand your question correctly this can be done using a bit of vector math. I've created an example in Javascript so please keep in mind that many of the mathematical operations I'm doing here can be done in Unity really easily using the built-in classes and methods. The ball will follow your mouse when you hover it over the window. I recommend you ...


0

Instead of hard restrictions you can use opposing forces. You want to simulate a rubber band between the two objects. That sort of force can be simulated by applying a push every frame that equals "distance to object" to the power of "your rubber band's springiness". If you want to increase the effective distance that object A can travel away from object B ...


3

You actually do not need C++/CLI for this, although you could use it if you wanted. I don't really recommend it. C#'s platform invoke facilities should be sufficient for you. You'll need to make your engine available as a DLL. Doing so is beyond the scope of this question, but there's plenty of information about making DLLs available on the web. Once you ...


5

Although I wholeheartedly agree with @Jon on this one I'm still going to answer your question. The following class will write to a file in the Update method. Have fun with it. using UnityEngine; using System.IO; public class VeryBadIdea : MonoBehaviour { private string filename = "WeWLad.txt"; private float some_variable; private string ...


4

You do not want to write to a file inside of Update(). That is bad design, and ridiculous. Instead, you may want to consider writing to memory in your Update() function -- and then dumping this data to file at a reasonable opportunity.


0

This is actually pretty easy in Unity, as Vector3 has a helper method called Distance Assuming A, B, and C are all GameObjects, you're using C#, and measuring the distance to A, your method can then look something like this: public GameObject Closest() { float distToB = Vector3.Distance(A.transform.position, B.transform.position); float distToC = ...


4

It has been a while since I've touched Unity, but this should get you in the right direction. Assuming A, B, and C are objects, and we want to see if B or C are closer to A: var BtoA = (B.position - A.position).magnitude; var CtoA = (C.position - A.position).magnitude; // Assume B should return if distances are equal if(BtoA <= CtoA) { // B is ...


0

I'd write a little script like this and attach it to the object displaying the sprite: [RequireComponent(typeof(SpriteRenderer))] public class SpriteSwitcher : MonoBehaviour { // Populate this array in the Unity Inspector window // to contain the sprites you want to switch between. public Sprite[] sprites; SpriteRenderer _spriteRenderer; ...


0

Application.Quit() method should be inside the Update() message inside a conditional statement wating becoming true to end the application.


1

I'm part of the customer success team at gamesparks.com Rest is generally reserved for server to server communication and it would be considered bad practice to use it in your unity client as it adds additional and unnecessary steps. My advice would be an event that constructs the NoSQL query from data passed as attributes into the event. The query can be ...


2

You can check for some button in Update(), for example, Esc (PC) or Back (Mobile): void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } }


2

Use the code below public void QuitGame() { Application.Quit(); }


3

You could generate a list of values you want to use, and then pick one at random. Create values: int[] values = new int[17] { 0,1,2,3,4,5,6,7,10,11,12,13,14,15,16,17,18,19,20 }; Get a random value: int value = values[Random.Range(0, values.Length)];


2

I guess you should go with a solution like this: int[] validChoices = new int[n]= {1,3,5, whatever until n occurrences}; private int GetRandom(){ return validChoices[Random.Range(0, validChoices.Length)]; }


6

Instead of throwing away numbers you don't want, you can pretend you want a number from one slightly smaller range, and then map it into the 2 ranges you want: float val = Random.Range( 1, 20 - 8 + 6 ); if ( val >= 6 ) val += 2;


-2

You can make a loop which creates random numbers until you're satisfied with the generated number. Code: float value; do { value = Random.Range(1, 20); } while (value >= 6 && value <= 8); Hope this helps


0

I think the best way to approach this would be to create a grid system where each square is 64x64 pixels, and then have your button press increment the square number. So the frog technically moves 64 pixels, but in code all you'd be doing is saying gridSquaresX + 1 or something.


1

Your code, as it is, isn't actually moving anything. You're assigning a Vector3 and modifying it's Y value, but you're not altering the Y value of the GameObject's transform. Having said that, you can't simply say: transform.position.y = y; Because Unity won't let you. Best way to do this for a beginner would be: void Awake() { int y = Random.Range(...


2

In Unity, the Vector3 type is a structure, not a class. In C#, structures are value variables, not reference variables. That means the = operator creates a copy. In the line Vector3 temp1 = transform.position; you are creating a copy of the position. Any changes at that copy are not reflected in the original position. When you want to modify the position, ...


0

I figured out how to solve this problem with the help of Kelv.Gonzales. I let the animation play for a set amount of time as I knew that it would last 0.9 seconds. This is the whole piece of code for this problem. //Running and jumping animation if (Input.GetKey (KeyCode.W) && (Input.GetKeyDown (KeyCode.Space)) && otherAnimation == false)...


0

There's nothing particularly special in how font rendering is handled in OpenTK. OpenTK - among other things - contains an OpenGL wrapper. And as such any techniques you'd use to render text in OpenGL apply here, namely: Using bitmap fonts - loading font atlas texture and rendering textured quads. BMFont Using geometric primitives (triangles/quads) to ...



Top 50 recent answers are included